8

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.

Saravanan Sachi
  • 2,572
  • 5
  • 33
  • 42
Boris
  • 602
  • 2
  • 8
  • 29

2 Answers2

18

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

Aakash Thakur
  • 3,837
  • 10
  • 33
  • 64
5

Correct syntax :

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