Reputation: 87
I'm looping over an array that contains a varying amount of percentages. However, I would like to add classes based on if an answer from the database equals one of the values from the array.
The below example loops over the values in the array. What i'm trying to do is say, 'if the answer is '0', apply a class with the name 'red', if not, add a class of 'transparent'. If the answer happens to be '20', add a class name of 'amber'. If not, 'transparent'.
I seem to be hitting a wall with the multiple variations that i'm trying.
<div *ngFor="let percent of percentages"
[ngClass]="{
(answer =='0') ? 'red':'transparent',
(answer =='20') ? 'amber':'transparent',
}">
{{ percent }}
</div>
EDIT - For clarification What I'm attempting to do is simplify the below. This is writing each of the percentages as it's own div. What I'm attempting to do is achieve the same result but by looping through an array of percentages instead.
<div [ngClass]="answer==='0' ? 'red' : 'bg-transparent'"> 0% </div>
<div [ngClass]="answer==='25' ? 'amber' : 'bg-transparent'"> 25% </div>
<div [ngClass]="answer==='50' ? 'orange' : 'transparent'"> 50% </div>
Upvotes: 0
Views: 8890
Reputation: 58039
there're a syntax for ngClass that is {'class1':condition1,'class2':condition2...} So I think that is more indicated
<div class="transparent" [ngClass]="{'red':answer == '0',
'amber':answer == '20',
'orange':answer==50}">
Upvotes: 0
Reputation: 17610
put other condition to else option part demo
<div *ngFor="let percent of percentages"
[ngClass]="(answer =='0') ? 'red': (answer =='20') ? 'amber':'transparent ">
{{ percent }}
</div>
Upvotes: 3
Reputation: 3418
How about moving your condition in your component rather than in template?
Something like this
// template
<div *ngFor="let percent of percentages"
[ngClass]="foo(answer)">
{{ percent }}
</div>
foo(answer) {
if(answer === '0') {
return 'red';
}
if (answer =='20' ) {
return 'amber'
}
// add more condition here or use a switch statement above.
return 'transparent';
}
Upvotes: 0
Reputation: 2396
You can use Ternery operator
<div *ngFor="let percent of percentages"
[ngClass]="{ answer == '0' ? 'red' : answer == '20' ? 'amber' : 'transparent'}">
{{ percent }}
</div>
Upvotes: 0