Reputation: 1309
I have a counter that counts down to 0, and I wanted to set the background color of an element according to the counter value:
What I did is to apply 3 different classes to the element and give a different condition to each one of them:
<p [class.green]="20 <= counter" [class.orange]="10 <= counter && counter <= 20" [class.red]="10 > counter">
{{ counter }}
</p>
Is there a better (or at least more corrected) way to achieve the desired outcome?
Upvotes: 1
Views: 2572
Reputation: 293
IMHO it's ok.
An alternative would be to have a function in the component and assign an attribute which would be 'orange', 'green' or 'red', and just use that attribute in the class such as class="{{statusAlert}}". Just an alternative, if you want to have all checkers in the model and not in the template. If you do it like so, that var could be reusable for other elements in your template, whereas using your approach, you should implement it for each element you want to assign that class.
Upvotes: 0
Reputation: 21564
Well I think about a more concise way using an [ngClass]
binding:
[ngClass]="counter>=20?'green':counter>=10?'orange':'red'"
Note that you should avoid putting too much logic inside your template to make it more readable and easier to understand. maybe using a method in your component :
component.ts :
getColor(counter){
return counter>=20?'green':counter>=10?'orange':'red';
}
template :
[ngClass]="getColor(counter)"
Upvotes: 2