MisterniceGuy
MisterniceGuy

Reputation: 1786

How can i change color of mat-icon in mat-table based on value in cell

How can i specify the color of an mat-icon in mat-table ? I have a color called dflt which is either true or false and i want to display either a green check or a red close. In my code currently i use

<ng-container matColumnDef="dflt">
            <th mat-header-cell *matHeaderCellDef> Default </th>
            <td mat-cell *matCellDef="let element"> <mat-icon>{{element.dflt ? 'check' : 'close'}}</mat-icon>{{element.dflt}} </td>
          </ng-container>

since if i want to for example change to red i would have to use color="warn". So how can i specify a different image based on the value as well as a different color ? I tried something like this but that does not work.

<td mat-cell *matCellDef="let element">{{element.dflt ? '<mat-icon color="warn">check</mat-icon>' : '<mat-icon color="primary">close</mat-icon>'}} </td> 

Upvotes: 0

Views: 2264

Answers (2)

Emilien
Emilien

Reputation: 2761

You just had to put a class into your mat-icon like this :

<mat-icon [color]="element.dlft ? 'warn' : 'green'">...</mat-icon>

Upvotes: 0

randombits.dev
randombits.dev

Reputation: 1356

You can just use *ngIf in the cell:

<ng-container matColumnDef="dflt">
  <th mat-header-cell *matHeaderCellDef> Default </th>
  <td mat-cell *matCellDef="let element"> 
    <mat-icon *ngIf="element.dflt" color="warn">check</mat-icon>
    <mat-icon *ngIf="!element.dflt" color="primary">close</mat-icon>
  </td>
</ng-container>

https://stackblitz.com/edit/mat-table-cell-icon-color?embed=1&file=app/table-example.html

Upvotes: 4

Related Questions