Reputation:
How can I add / remove a class in html
element, based on the value assigned in a variable in the model. For example, I have a value
variable inside of my Angular component:
export class SomeComponent implements OnInit {
value: number = 6;
...
}
Now, based on the value (which is updated quite often via an event listener), I want to add / remove a class in the html
element when the condition is true:
<div [ngClass]="value >= 3 ? 'bordered-section' : ''"></div>
<div [ngClass]="value >= 6 ? 'bordered-section' : ''"></div>
I think I managed to make this work on initialization, but when the variable changes again, the classes are not removed. How can I solve this?
Upvotes: 4
Views: 8888
Reputation: 24414
Try this way
<div [ngClass]="{'bordered-section1' : value == 3 , 'bordered-section2' :value > 5 }"></div>
also this way possible
<div [ngClass]="{'bordered-section' : value >= 3 || value <=6 }"></div>
you can add or remove class based on boolean expression with ngClass directive
Upvotes: 1
Reputation: 2966
<div [ngClass]="{'bordered-section' : value >= 3 }"></div>
<div [ngClass]="{'bordered-section' : value >= 6 }"></div>
Should work by this way, ngClass
should get an Object with classes names
Upvotes: 5