angular – What is the command using *ngIf to do a major and minor check

Question:

I'm using ngIF just to change the object's color, but I'm needing to create one where the result.MediaTotal is less than 70 and greater than 50. What is the correct syntax to do this: *ngIf="result.MediaTotal < 70 and > 50"

<p *ngIf="resultado.MediaTotal > 70" style="color:green">{{resultado.MediaTotal}} </p>

Answer:

I recommend using ngClass instead of ngIf to style your components dynamically. Let's imagine a scenario where you have multiple styles, you would have to make multiple components the same just changing their style, this is bad practice as you are repeating code.

Example:

<p [ngClass]="getClass()">{{resultado.mediaTotal}}</p>

Note that we are not doing any validation in the html, we can leave this part to component , where in this example I created the function getClass()

In your Component/Page you would do something like:

 getClass(){
    if(this.resultado.mediaTotal > 50 && this.resultado.mediaTotal < 70)
      return 'my-style-green'
    if(this.resultado.mediaTotal < 50)
      return 'my-style-red'
  }

Note that it is returning a string, this string is your class that you can put in your page's css.

.my-style-green{
     color: green;
 }
 .my-style-red{
     color: red;
 }
Scroll to Top