I have a condition in my html template that loops through an object and create a list of items. I have studied [NgClass] because I need to set the class of a row based on a condition of that particular item. So my understanding and testing shows that NgClass is set once based on a variable. I want it to check during every loop if true/false. So basically I want
<div [ngClass]="{'redclass': {{hour.enoughrest}}}"> However this of course do not work. Any ideas? I have feeling the solution is obvious but I am at loss.
4 Answers
There are several ways to change class dynamically.
<div [ngClass]="{'redclass': hour.enoughrest}">
Or
[class.redclass]="hour.enoughrest"
Or if you want to add class based on condition
<div [className]="condition ? 'example-class' : 'other-class'"></div>
In addition to that you can change NgStyle dynamically and update style as bellow if you want to do style changes.
<p [ngStyle] = “{backgroundColor : getColor() }” >
in .ts file
getColor() {
return this.serverStatus === ‘online’? ‘green’: ‘red’;
}
{{hour.enoughrest}}<div [ngClass]="{'redclass': hour.enoughrest}">