简体   繁体   中英

How to find min , max on array and how to change color text for min green color and max red color using angular

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 } .... ... { itemId: "555", category: 'B', total: 2 } ]

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 find min total and change color to green. I want to find also max total and change color red.

Please, have you any idea how to make this?

So, this question has two parts, right ? The first one is sorting and the second one is changing the first and last items green and red .

For Sorting, you can use this

items = items.sort((fstItem, secItem)=> fstItem.total > secItem.total ? 1 :
fstItem.total < secItem.total -1 : 0 );

for second thing, you can use in html with first and last index from *ngFor

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM