Lets say I have some objects in an array (lets call the array "items") like { title: "Title", value: true }
and I use ngFor to display them like:
<h1 *ngFor="let item of items">{{ item.title }}</h1>
Now lets say I want to display a class on the h1 based on if item.value is true or false. How can I do that?
I can't add [class.some-class]="{{ item.value }}"
. Basically, how can I get the true or false value for the current item into something like ngClass? Am I missing an obvious way to do this in Angular 2?
(Btw, I know I can do it by adding class="{{ item.value | pipe }}"
to the h1 and piping the value and returning the correct class based on the values true and false, but it seems like there should be a better way.)
Thanks
You shouldn't interpolate it. Just leave out the {{}}
. This will interpolate it to a string. Leaving those out will give you the boolean value, which is perfectly valid for [class.some-class]
[class.some-class]="item.value"
Other options
You can also use object notation either inline or taken from the component, if you have a few different classes. Basically the property is the css class, and the value is the true/false
[ngClass]="{'some-class': item.value }"
Or get the object from the component
getClasses(value) {
return { 'some-class': value }
}
[ngClass]="getClasses(value)"
See Also
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With