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 can add a conditional class like this:
<h1 *ngFor="let item of items"
[class.some-class]="item.value === true">
{{ item.title }}
</h1>
Remember that the *ngFor
syntax actually expands into a template
. In your example, it would expand into:
<template ngFor let-item [ngForOf]="items">
<h1 [class.some-class]="item.value === true">
{{ item.title }}
</h1>
</template>
When you see it expanded, you can see why you're able to use the [class.xyz]
directive with a template input variable of the item
.