Reputation: 609
I wanted to style the html elements based on array index value > 4
<div *ngFor="let e of arr ; let i = index" >
(i > 4 ) ? <p [ngClass]="['clr']" [ngStyle]="{'background-color': 'blue'}"> {{e}} </p> : <p> {{e}} </p>
</div>
I wanted to check condition inside the loop. But it just printed as string with out checking condition.
Upvotes: 0
Views: 606
Reputation: 3062
The least verbose way would probably be to simply put the conditional inside the ngClass or ngStyle statement.
[ngClass]=" i > 4 ? 'whateverClass' : 'whateverOtherClass'"
or
[ngStyle]="{'background-color' : ((i > 4) ? 'blue' : 'red') }"
Or any variation of these
Upvotes: 1
Reputation: 62308
One way to solve it is using *ngIf
<div *ngFor="let e of arr ; let i = index">
<p *ngIf="i > 4" [ngClass]="['clr']" [ngStyle]="{'background-color': 'blue'}"> {{e}} </p>
<p *ngIf="i <= 4"> {{e}} </p>
</div>
Another is to use conditional classes using ngClass
<div *ngFor="let e of arr ; let i = index">
<p [ngClass]="{'clr-blue' : i > 4}"> {{e}} </p>
</div>
Upvotes: 3