Home > Enterprise >  Using ngClass with positive and negative numbers and change color in Ionic/Capacitor
Using ngClass with positive and negative numbers and change color in Ionic/Capacitor

Time:06-20

I have a data element from my api to show the price and some percentage data. Based on the number I want to give the negative numbers red and 0 and above green. I saw on the Angular documentation you can use ngstyle and ngClass. I decided to choose ngClass so I can reuse the code for other pages. This is what I have:

<ion-row>
  <div>{{Prices}}</div> 
</ion-row> 

And

<ion-row>
      <div>{{PricesPercentage}}</div> 
</ion-row> 

The data looks like this:

Price:

1304.53

PricesPercentage:

2.33906, -0.04118

When it's negative I want to give the css class red.

.green-color{
 color:green;
}

.red-color{
    color:red;
}

I have searched on google for solution and this is what I have tried:

Solution 1: using function

 checkNumberColor(numberCheck) {
    if (this.numberCheck >= 0,0) {
      return 'green-color';
    }
    if (this.numberCheck < 0,0) {
      return 'red-color';
    }   
  }

And I bind this like:

  <div [ngClass]="checkNumberColor(PricesPercentage)">{{PricesPercentage}}</div> 

I have tested this and didn't work. No errors in the chrome dev tools.

Angular 2 ngClass function

Solution 2: condition on the ngClass itself

<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?

And I use this documentation to convert ngClass to a newer version:

https://angular.io/api/common/NgClass

I prefer solution 2 to work. When I open my app it doesn't change the color.

Can someone point me in the right direction?

CodePudding user response:

Your implementation of the [ngClass] is wrong. Here is how you should do it. [ngClass]="PricesPercentage > 0 ? 'green-color' : 'red-color'"

Here is a link to a stackblitz I created now to help you see the [ngClass] in action.

  • Related