0

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

lona bin
  • 25
  • 6

2 Answers2

0

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>
Xavier Brassoud
  • 697
  • 6
  • 14
0

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>
Muhammet Can TONBUL
  • 3,217
  • 3
  • 25
  • 37
  • Thank you for your comment, but I have a lot of data, and from those data I want to color only min total and max total. I don't know which are totals number. I want something dynamic – lona bin Oct 13 '21 at 14:04
  • Actually, your question has been answered by me and @Xavier Brassoud below. Maybe you want something different. It would be helpful if you could explain your question more clearly. – Muhammet Can TONBUL Oct 13 '21 at 14:06
  • Yes you are right. Maybe should be get min and max of total – lona bin Oct 13 '21 at 14:09
  • I edit my question. If you can please help me. Thnaks – lona bin Oct 13 '21 at 14:15