Boris
Boris

Reputation: 641

Angular 2, using ngClass with conditionals in ngFor

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.

Upvotes: 9

Views: 22228

Answers (2)

Aakash Thakur
Aakash Thakur

Reputation: 3895

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

Upvotes: 19

user4676340
user4676340

Reputation:

Correct syntax :

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

Upvotes: 6

Related Questions