forgottofly
forgottofly

Reputation: 2719

Set dynamic class based on index in angular ngFor

I'm trying to set class for elements inside ngFor but changes are not reflecting as this class declaration class="car-title{{index}}" seems to be not working .

I have given equivalent colors as shown below for car title that needs to be displayed based on the index value inside ngFor.

                .car-title1 {
                    color: blue;
                }
                 .car-title2 {
                    color: red;
                }
                .car-title3 {
                    color: green;
                }

Plunker link here

Upvotes: 4

Views: 13390

Answers (3)

Santhosh R
Santhosh R

Reputation: 31

Works Fine

*ngFor="let item of items; let i = index"

[class]="'car-title'+(i+1)"

OR

[ngClass]="'car-title'+ i"

Upvotes: 2

Mike Trinh
Mike Trinh

Reputation: 1303

The right way to do this is to use ngClass

*ngFor="let item of items; let i = index"

[ngClass]="'car-title'+ i"

Upvotes: 7

Danylo Gudz
Danylo Gudz

Reputation: 2656

user class binding

[class]="'car-title'+(index+1)"

Upvotes: 8

Related Questions