I am trying to change the color backround of an element based on a condition. For example if number >2, color green. My css:
.color-green {
background-color: green;
color: white;
}
<h9>My number{{ data.number}}</h9>
I tried with ng-class but does not work. What am I missing here?
<td ng-class = "{'color-green':data.number>=2}"> <h9>My number {{ data.number}} </h9></td>
Or what would be the simplest way to achieve this?
CodePudding user response:
You need to change ng-class
with [ngClass]
:
<td [ngClass]= "{'color-green':data.number>=2}"> <h9>My number {{ data.number}} </h9></td>
Reason: ng-class
was used in angularJS. [ngClass]
is used in Angular 2 .
CodePudding user response:
Do it like in Angular Documentation:
<td [ngClass]="data?.number >= 2 ? 'css-class-one' : 'css-class-two'"></td>
Also, use the optional chaining operator to prevent run time undefined issue on your number property. Do it with this ? marke like this data?.number
CodePudding user response:
Your changes do look correct, can you inspect in the browser to see if your class is getting applied on the element and if your defined class is accessible?