1

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:

  • Green: 20 or higher
  • Orange: 10 to 20
  • Red: 9 or lower

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?

2

2 Answers 2

2

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

Comments

0

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.

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.