Angular 2, using ngClass with conditionals in ngFor

BrS picture BrS · Jun 30, 2017 · Viewed 14.2k times · Source

I have ngFor loop that displays data, and based on if something is true or false in that loop, how can I change css? What I tried, does not work for me.

HTML

<div class="class" *ngFor="let something of something" [ngClass]="{'classno2': sent}">
    <div> {{something.name}}
    </div>
</div>

TypeScript

something;

this.something = [
    {name: "NAMEE", sent: false},
    {name: "NAMEE2", sent: true},
]

CSS

.class {
    color: red;
}
.classno2 {
    color: blue;
}

I get no errors, but yet nothing changes.

Answer

Aakash Thakur picture Aakash Thakur · Jun 30, 2017

You can use [ngClass] like this:

<div *ngFor="let some of something" [ngClass]="{'classno2': some.sent, 'class': !some.sent}">
    <div> {{some.name}}
    </div>
</div>

Above will take care of styling based on whether sent is true/false.

Working plunker:https://plnkr.co/edit/45regTAQvbCu61kvUAlJ?p=preview