Home > Enterprise >  How to change color text when using ngClass inside *ngFor
How to change color text when using ngClass inside *ngFor

Time:10-14

I want to change color of text when using ngClass.

I have the JSON like below but I have a lot of data:

items: [ { itemId: "22222", category: 'A', total: 100 }, { itemId: "666666", category: 'A', total: 80 }, { itemId: "555", category: 'B', total: 50 } ]

I create on .scss

   &.is-green {
      color: green;
    }
    &.is-red {
      color: red;
    }

I want to use it something like that:

<div *ngFor="let item of items;> 
    <div>{{item.category}}</div>
    <div 
      [ngClass]="{
        'is-green': item.total ,
        'is-red':item.total
         }"
       >
       {{item.total}}</div>
    </div>

From this data I want to display total with min value exp total: 50 color green and total with max value exp total: 100 color red

CodePudding user response:

Access directly to the class attributes:

<div *ngFor="let item of items;> 
    <div>{{item.category}}</div>
    <div [class.is-green]="item.total <= 50" [class.is-red]="item.total > 50" >
        {{item.total}}
    </div>
</div>

CodePudding user response:

Here is the answer of how to conditionally add classes.

https://stackoverflow.com/a/41974490/6478359

I have prepared a sample project for your problem.

https://stackblitz.com/edit/angular-ivy-cjpr4v

<div *ngFor="let item of items">
  <div>{{ item.category }}</div>
  <div
    [ngClass]="{
      'is-green': item.total === 50,
      'is-yellow': item.total === 80,
      'is-red': item.total === 100
    }"
  >
    {{ item.total }}
  </div>
</div>
  • Related