Adjust the colors dynamically based on specific data within a loop

My task involves populating a table with data. Specifically, I am focusing on coloring the data in the first year column according to certain conditions. The desired outcome is as follows:

+--------+------------+------+------+
| YEAR   | 2022       | 2021 | 2020 |
+--------+------------+------+------+
| First  | 0.2(color) | 0.5  | 0.8  |
+--------+------------+------+------+
| Second | 0.1(color) | 0.4  | 0.5  |
+--------+------------+------+------+
| Third  | 0.3(color) | 0.9  | 0.2  |
+--------+------------+------+------+
| Fourth | 0.2(color) | 0.1  | 0.8  |
+--------+------------+------+------+
| Fifth  | 0.6(color) | 0.4  | 0.2  |
+--------+------------+------+------+

The current method I have been using is displayed below:

+--------+------------+------------+------------+
| YEAR   | 2022       | 2021       | 2020       |
+--------+------------+------------+------------+
| First  | 0.2(color) | 0.5(color) | 0.8(color) |
+--------+------------+------------+------------+
| Second | 0.1        | 0.4        | 0.5        |
+--------+------------+------------+------------+
| Third  | 0.3        | 0.9        | 0.2        |
+--------+------------+------------+------------+
| Fourth | 0.2        | 0.1        | 0.8        |
+--------+------------+------------+------------+
| Fifth  | 0.6        | 0.4        | 0.2        |
+--------+------------+------------+------------+

Due to the unpredictable nature of changes in the first child element (as there is an arrow for navigating through displayed years), CSS alone cannot achieve this effect.

Sample HTML snippet:

<tbody>
    <tr *ngFor="let row of titles">
        <td>{{ row.title }}</td>
        <ng-container *ngFor="let year of data">
            <td [ngClass]="row.className">{{ year[row.dataFill]}}</td>
        </ng-container>
    </tr>
</tbody>

List of columns:

export const titles = (className) => [
{title: "First Title", dataFill: "first", className: className},
{title: "Second Title", dataFill: "second", className: className},
{title: "Third Title", dataFill: "third", className: className},
{title: "Fourth Title", dataFill: "fourth", className: className},
{title: "Fifth Title", dataFill: "fifth", className: className}
]

Related TypeScript function:

colorChange() {
    const green = 'green';
    const red = 'red';
    const black = 'black';
    
    this.titles.map(x => {
    if(x.dataFill == 'first') {
        if(this.data[0].first < this.data[1].first) {
        x.className = green;
        }
        else if(this.data[0].first > this.data[1].first) {
            x.className = red;
        }
        else {
        x.className = black;
        }
    //etc..etc..
    }
    return x;
  });   
}

Associated CSS styling:

.green {
    color: green;
}
.red {
    color: red;
}
.black {
    color: black;
}

Answer №1

To optimize your [ngClass] functionality, consider enclosing the expression in double curly braces to properly incorporate TypeScript into your HTML code. Here's how you can modify it:

[ngClass]="{{row.className}}

Furthermore, please note that there is a typo in your last else statement with blackl, where an extra "L" has been mistakenly added.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to display toast notification in React/MUI/Typescript project

Currently tackling error notifications targeted at 400,401, and 500 errors within a large-scale project. I am facing an issue where I want to integrate my ErrorToastNotification component into my layout.tsx file to avoid duplicating it across multiple page ...

Showing information from Flask API utilizing Angular with underscores

I'm in the process of creating components from my Flask API. Upon accessing the route, I can view the data for the desired objects. However, upon attempting to display it on the front end through interpolation, I am only able to see certain properties ...

Is it possible to apply two ngClass directives to a single div element in Angular 4?

When I click to start editing, a component is called for the editing process. In this component, I am unable to click on anything and the background turns black, which is okay. However, I would like for each ID that I select to edit to become active with a ...

Is it possible for pdfjs-dist to be used with Typescript?

Is there a way to preview a PDF as a canvas without importing pdfjs-dist into my project? I have already used the command $yarn add pdfjs-dist to install pdfjs-dist. Do I need to include any additional imports? import pdfjsLib from "pdfjs-dist/build ...

Webpack is encountering difficulties in locating the entry module when working with typescript

I've been working on integrating webpack into my typescript application. To get a better understanding of webpack, I decided to do a minimal migration. I started by cloning the Angular2 quickstart seed and added a webpack.config.js: 'use strict& ...

Error: Unable to access $rootScope in the http interceptor response function

I have set up an interceptor to display an ajax spinner while loading. interface IInterceptorScope extends angular.IRootScopeService { loading: number; } export class Interceptor { public static Factory($q: angular.IQService, $ro ...

Having trouble installing memlab using the npm package

Recently, I made an attempt to install the memlab library from Meta's GitHub. Initially, when I installed it without using the -g flag, the installation was successful. However, I encountered an issue where I could not execute any of the memlab comman ...

What is the best way to create an array of strings that can include multiple elements from a set of strings?

Exploring different roles for authorization: ['admin', 'manager', 'user'] Is there a way to create a specific type, named Roles, which is essentially a string array ( string[] ) that is limited to only containing values from ...

Monitor constantly to determine if an element is within the visible portion of the screen

For a thorough understanding of my query, I feel the need to delve deeper. While I am well-versed in solving this issue with vanilla Javascript that is compatible with typescript, my struggle lies in figuring out how to invoke this function throughout th ...

Problem with Clerk's authentication() functionality

Currently facing an issue with the Clerk auth() helper (auth() documentation) while working with react and next 13 (app router). When trying to access both userId and user from auth(), const { userId, user } = auth();, it seems that userId contains a val ...

Leveraging parameters within a sequence of object properties

Within the realm of Angular, I am dealing with interfaces that take on a structure similar to this (please note that this code is not my own): export interface Vehicles { id: number; cars: Car; trucks: Truck; } Export interface Car { make: ...

Angular components are not properly adhering to the specified height and width dimensions for child elements

I seem to be having trouble applying height/width to a child component in angular. Can someone take a look and point out where I may have gone wrong? app.component.html <app-child [width]="10" [height]="10"></app-child> .child.ts import { C ...

Typescript combined with MongoDB models

One common issue I have encountered involves a method used on my repository: async findByEmail(email: string): Promise<User | null> { const user = await UserModel.findOne({ email }); if(!user) return null; ...

What is the reason behind Angular generating files with 'es5' and 'es2015' extensions instead of 'es6' (or no extension)?

Recently, I installed the Angular CLI (@angular/cli 9.0.1). My goal was to create a new Angular Element, package it, and then integrate it into another application. Following several blog tutorials, I found that they all mentioned the final step of creati ...

I'm looking to enhance security in my sign-up form by adding a custom shield using Angular for my Firebase database. How can

I recently followed a tutorial to build my angular app with firebase authentication. Currently, everything is functioning correctly. However, This is the first time I am attempting to create a genuine sign-up form with custom fields and integrate them i ...

Troubleshooting Angular 2: Why Array Interpolation is Failing

Greetings everyone, I am diving into Angular 2 and attempting to create a basic Todo application. Unfortunately, I've hit a roadblock. My array interpolation seems to be malfunctioning. Any assistance would be greatly appreciated. Here is my AppCompo ...

How can a single variable be assigned one of two potential @Inputs in Angular2+?

Currently, I am facing a challenge in defining inputs for an Angular8 Directive while also supporting a legacy Directive. My plan going forward is to name my inputs in camel-case, but the existing inputs are in kebab-case. Therefore, in order to support th ...

When ts-loader is used to import .json files, the declaration files are outputted into a separate

I've encountered a peculiar issue with my ts-loader. When I import a *.json file from node_modules, the declaration files are being generated in a subfolder within dist/ instead of directly in the dist/ folder as expected. Here is the structure of my ...

Tips for verifying the variable type in a TypeScript ESLint custom rule

Trying my hand at creating a custom TypeScript-eslint rule that requires the callee's object of a node to be of a specific type, which I'll refer to as MyType. Utilizing the CallExpression from typescript-eslint in the code snippet below: Source ...

The declaration file for the module 'vue-html-to-paper' was not located

Struggling to make a sample project work with HTML to PDF, but encountering an error message stating: Could not find a declaration file for module 'vue-html-to-paper' Even though it resides in my node_modules index.js import Vue from 'vue& ...