0

The case here is I want to assign colour to each row of mat table based on some logic (for e.g orderId of the list) for orderId <= 1000 colour should be red, for 1000 < orderId <= 2000, colour should be green and orderId > 2000, colour should be yellow. I tried this but unable to achieve the desired output:

<mat-row *matRowDef="let row; columns: displayedColumns" 
         (click)="highlightedRows.push(row)" 
         [style.background]="highlightedRows.indexOf(row) != -1 ? backgroundColor : ''">
</mat-row>

Any help will be appreciated.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
karan1131
  • 31
  • 1
  • 7

3 Answers3

1
<mat-row *matRowDef="let row; columns: displayedColumns; let i = index"         
         [style.background]="getBackgroundColour(i)">
</mat-row>
getBackgroundColour(i) {
    if(i <= 1000) {
        return 'red'
    }
    if(i <= 2000) {
        return 'green'
    }
    if(i > 2000) {
        return 'yellow'
    }
}
Sam
  • 1,736
  • 8
  • 15
0

Call a function in html

<mat-row *matRowDef="let row; columns: displayedColumns" (click)="highlightedRows.push(row)" [style.background]="setBgColor(row.orderId)"></mat-row>

and in your ts you can add a function

  setBgColor(orderId: number){
    if(orderId <= 1000){
      return "#ff0000";
    }
    else if(orderId  <= 2000 && orderId > 1000){
      return "#008000";
    }
    return "#ffff00";
  }
Faizan
  • 1,132
  • 2
  • 12
  • 23
0

You can use ngClass for this. This will require to make css classes with the required color.

Then after this you need to do:

<mat-row *matRowDef="let row; columns: displayedColumns" (click)="highlightedRows.push(row)" 
[ngClass]="{'redClass': row.orderId <= 1000, 'greenClass': row.orderId > 1000 && row.orderId <= 2000, 'yellowClass': row.orderId > 2000}">

Source: Multiple conditions in ngClass - Angular 4

Swoox
  • 3,707
  • 2
  • 21
  • 32