Adjusting ngClass dynamically as values change

Currently, I am facing a situation where I want to dynamically add a class to my view using ngClass based on changes in the output value. The output value is dependent on the response received from an API, and I am fetching data from the endpoint every second for a Simple Forex Application.

Initially, I attempted two-way data binding with ngModel and events, but I encountered screen flickering issues.

I would greatly appreciate any advice or suggestions on how to handle this scenario.

Below is a snippet of the code:

<tbody>
    <tr *ngFor="let data of tableData">
    ..........
    <td>{{ data.price }}</td>
    </tr>
</tbody>

My goal is to assign a class to the data.price value based on its changes. For instance, if the initial value is 100, and on the next response it becomes 101, I want to apply a green background class. Similarly, if the value reduces to 99, I would like to add a red background class. However, due to the data changing frequently every second, I am struggling to manage the state and apply the appropriate classes.

Answer №1

Without any code examples provided, let's assume we are using a div as the selector. Here is an example:

<div [class.className]="logicWhenTrue" [class.className]="logicWhenFalse">Content </div>
.className will be applied to the element if the logic evaluates to true, otherwise it will be ignored. This method allows for conditional class assignment based on different logics.

UPDATE

Consider the following:

.blue {
  background: blue;
}

.yellow {
  background: yellow;
}
<tbody>
<ng-container *ngFor="let data of tableData">
  <tr [class.blue]="data.price > 150" [class.yellow]="data.price < 150">
    .......... 
    <td>{{ data.price }}</td>
  </tr>
</ng-container>
</tbody>

This will apply the classes based on the condition logic.

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

Include the designated return type within a fat arrow function

No matter how hard I look, I cannot figure out the correct way to combine return type annotation with fat arrow syntax. class BasicCalculator{ value:number; constructor(value:number=0){ this.value=value; } add= (operand:number)=> ...

Triggering multiple updates within a single method in Angular will cause the effect or computed function to only be triggered

Upon entering the realm of signals, our team stumbled upon a peculiar issue. Picture a scenario where a component has an effect on a signal which is a public member. In the constructor of the component, certain logic is executed to update the signal value ...

Is it possible to meet the requirements of a specific interface using an enum field as the criteria?

I've been struggling to create a versatile function that can return a specific interface based on an enum argument, but all my attempts have failed. Could it be possible that I missed something or am simply approaching it the wrong way? If I try to ...

Prevent ASP.NET Core routing from intercepting Angular 5 routing calls during deep linking operations

I am currently utilizing ASP.NET Core MVC for managing API calls, with routing set to api/*. Additionally, Angular 5.x is being used alongside its own routing system. Everything functions smoothly when running locally (Core on port 5000 and Angular on 420 ...

Update header component dynamically upon successful login with Angular 11

I am currently using Angular 11 and facing an issue with displaying the username in the header component. The header loads before the login component, which results in the user data being stored in local storage only after the login component is loaded. As ...

Is it possible to combine Webpack 5 Module Federation micro frontends with Nx monorepos?

Exploring the concepts of micro frontend and monorepo architecture in the context of an Angular 12 project. Recently, Webpack 5 has been deemed production-ready, introducing Module Federation as its solution for micro frontends. With Module Federation, the ...

issue with mongoose virtual populate (unable to retrieve populated field)

During my project using mongoose with typescript, I encountered an issue with adding a virtual called subdomains to populate data from another collection. Although it worked without any errors, I found that I couldn't directly print the populated data ...

Values within the inner *ngFor loop have been selected from the outer *ngFor loop

In our Angular 4 application, we are facing a specific requirement that needs to be addressed. We have successfully implemented *ngFor up to three levels and below is the code snippet for the implementation: <div *ngFor="let country of Countries"> ...

Double firing issue with ngModelChange when paired with ng DateTimePicker in Angular 7

When utilizing the ng datetimepicker library in Angular to display a date time picker, I'm experiencing an issue where the method triggered by (ngModelChange) fires twice simultaneously, causing the changed date to be logged twice in the console. Can ...

Excluding the decimal point from version 1.0 in an API response with Angular 5

When working with Angular 5, I encountered an issue where the API response was returned as 1.0, but when displayed in the HTML field it only showed as 1. Upon inspecting the response in Chrome dev-tools, under the Network tab -> Response, it correctly ...

Modify one specific variable within my comprehensive collection on Firebase Firestore

After clicking the button, I need to update a variable. The variable in question is "bagAmount" and it is stored in my firestore collection. Here is a link to view the Firestore Collection: Firestore Collection Currently, I am able to update one of the va ...

Understanding how to retrieve the value count by comparing strings in JavaScript

In my array object, I am comparing each string and incrementing the value if one letter does not match. If three characters match with the string, then I increase the count value; otherwise, it remains 0. var obj = ["race", "sack", &qu ...

Identify modifications to properties in Angular

What is the most effective method for responding to property changes within a component? I am seeking a solution that will trigger a specific function every time a property in a component is altered. Consider the following example with a single component: ...

Guide to customizing CSS styles within a div element using TypeScript code in a Leaflet legend

I'm struggling to add a legend to my map using Angular 5 and typescript. I need help with setting CSS styles for the values (grades) that are displayed on the legend. Can someone guide me on where to put the styles? TS: createLegend() { let lege ...

What is the best way to remove all attributes from one interface when comparing to another?

Consider the following two interfaces: interface A { a: number; b: string; } interface B { b: string; } I am interested in creating a new type that includes all the keys from interface A, but excludes any keys that are also present in interface B. ...

The error form is not responding even after attempting to locate the issue

I have created a form and it was working fine, but now when I click on the submit or reset buttons, nothing happens. I've checked my code thoroughly line by line, but can't seem to find the issue. I even tried restoring previous versions, but no ...

What is the best way to include a new attribute in a TypeScript internal object?

I am trying to include a property declaration in the window.history object, but I received a TypeScript error message This is my code: const historyInstance = createHashHistory(); // npm hoistory module window.history.historyInstance = historyInstance; / ...

Strategies for setting the output value for a defined generic type

Is there a way to create a function that accepts optional properties common across different types, while also requiring specific properties based on the generic type passed in? type Diff<T, U> = T extends U ? never : T type DiffTypes<T, U> = ...

API rest data retrieval service in Angular

I'm currently working on my first Angular App and I need to fetch data from another local API Rest. My project is inspired by the Angular tutorial tour-of-heroes. I have created a component service to make API calls and display the results in another ...

What sets apart window.location.href from this.router.url?

I'm curious about the various methods of obtaining the current URL in Angular. For instance: this.router.url My main question is: What advantages does using this.router.url offer over simply using window.location? Could someone kindly provide an exp ...