I have data from my API that includes price and percentage data. I want to display negative numbers in red, and zero or positive numbers in green. After exploring Angular documentation, I found that ngStyle and ngClass can be used for this purpose. I chose ngClass for code reusability across different pages. Here's what I have:
<ion-row>
<div>{{Prices}}</div>
</ion-row>
And
<ion-row>
<div>{{PricesPercentage}}</div>
</ion-row>
The data is as follows:
Price:
1304.53
PricesPercentage:
2.33906, -0.04118
I aim to apply the "red" CSS class to negative values.
.green-color{
color:green;
}
.red-color{
color:red;
}
After searching on Google, I attempted two solutions:
Solution 1: using a function
checkNumberColor(numberCheck) {
if (this.numberCheck >= 0,0) {
return 'green-color';
}
if (this.numberCheck < 0,0) {
return 'red-color';
}
}
I then bind it like this:
<div [ngClass]="checkNumberColor(PricesPercentage)">{{PricesPercentage}}</div>
Despite testing, it didn't work with no errors shown in Chrome Dev Tools.
Angular 2 ngClass function
Solution 2: condition within ngClass
<div [ngClass]="{'red-color' : (PricesPercentage) < 0.00, 'green-color' : (PricesPercentage) >= 0.00}">{{PricesPercentage}}</div>
How to use ng-class to achieve positive and negative styling angularJs?
I also utilized this documentation to update ngClass:
https://angular.io/api/common/NgClass
Solution 2 is my preference, but unfortunately, upon opening the app, the colors don't change. Can someone guide me in the right direction?