Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a material table cell's background color conditionally

Tags:

angular

in the example material table given here, if I want to change the background color of all cells that contain a value > 10, where would I put that code?


1 Answers

There are so many ways to do it. This is the one way to do it like in weight cell if value is greater than 10 then yellow color in background.

<ng-container matColumnDef="weight">
    <mat-header-cell *matHeaderCellDef> Weight </mat-header-cell>
    <mat-cell [ngClass]="{clsWeight: element.weight > 10}" *matCellDef="let element"> {{element.weight}} </mat-cell>
  </ng-container>

Here is the working demo

If you dont want to use ngClass then you can directly use the style like this

<ng-container matColumnDef="weight">
    <mat-header-cell *matHeaderCellDef> Weight </mat-header-cell>
    <mat-cell [style.background-color]="element.weight > 10 ? 'yellow' : ''" *matCellDef="let element"> {{element.weight}} </mat-cell>
  </ng-container>

Working Demo

like image 85
Vishal Mittal Avatar answered Dec 21 '25 07:12

Vishal Mittal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!