What command using *ngIf to do a larger and smaller check

Asked

Viewed 4,622 times

4

I’m using ngIF only to change the color of the object, but I’m needing to create one that 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>

2 answers

3

You must use the logical operator &&

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

3


I recommend using ngClass instead of ngIf to dynamically stylize its components. Let’s imagine a scenario where you have multiple styles, you would have to make multiple components equal by just changing their style, that’s bad practice because you’re repeating code.

Example:

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

Note that we are not doing any validation in html, we can leave this part pro 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;
 }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.