Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set dynamic class based on index in angular ngFor

Tags:

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

like image 283
forgottofly Avatar asked Dec 05 '22 13:12

forgottofly


2 Answers

user class binding

[class]="'car-title'+(index+1)"
like image 94
Danil Gudz Avatar answered Dec 30 '22 06:12

Danil Gudz


The right way to do this is to use ngClass

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

[ngClass]="'car-title'+ i"
like image 40
Mike Trinh Avatar answered Dec 30 '22 06:12

Mike Trinh