0

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.

2
  • Read through this article - you will get the answer - ng2.codecraft.tv/built-in-directives/ngstyle-and-ngclass Commented Jul 10, 2018 at 18:59
  • Can someone please help me to understand what is wrong in my approach. why it is printing string without checking the condition Commented Jul 10, 2018 at 19:24

2 Answers 2

3

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> 
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.