Reputation: 5048
How do I change the color of a material table row depending on a cell value.
I have this in my HTML:
<mat-table [dataSource]="dataSource" class="mat-elevation-z2" style="margin-bottom: 10px;" matSort>
<ng-container matColumnDef="DateAdded">
<mat-header-cell *matHeaderCellDef mat-sort-header> Submission Time </mat-header-cell>
<mat-cell *matCellDef="let row"> {{row.DateAdded | date: 'medium'}} </mat-cell>
</ng-container>
<ng-container matColumnDef="StartDate">
<mat-header-cell *matHeaderCellDef mat-sort-header> Start Date </mat-header-cell>
<mat-cell *matCellDef="let row"> {{row.StartDate | date}} </mat-cell>
</ng-container>
<ng-container matColumnDef="EndDate">
<mat-header-cell *matHeaderCellDef mat-sort-header> End Date </mat-header-cell>
<mat-cell *matCellDef="let row"> {{row.EndDate | date}} </mat-cell>
</ng-container>
<ng-container matColumnDef="IsGranted">
<mat-header-cell *matHeaderCellDef mat-sort-header> Granted </mat-header-cell>
<mat-cell *matCellDef="let row" [ngClass]="row.IsGranted ? 'make-green' : ''"> {{row.IsGranted}} </mat-cell>
</ng-container>
<ng-container matColumnDef="Remarks">
<mat-header-cell *matHeaderCellDef> Remarks </mat-header-cell>
<mat-cell *matCellDef="let row" [style.color]="row.color">
<button class="btn btn-dark btn-sm" (click)="viewRemarks(row.Remarks)">Select</button>
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns" [ngClass]="{'make-green': row.IsGranted==true}"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;">
</mat-row>
</mat-table>
<mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
And my CSS :
.make-gold {
background-color: gold
}
This produces the following result:
What I need is to change the background color of the whole row. Not just the cell. Thank you.
Upvotes: 35
Views: 84676
Reputation: 307
In my case, I wanted to change the row background color when the row id is 0. Here ngClass directive (angular doc) applies 'new-row' CSS class when the condition is true.
In table component
<tr mat-row *matRowDef="let row; columns: displayedColumns;" [ngClass]="{'new-row': row.id == 0 }"></tr>
CSS
.new-row {
background-color: #eef2f5
}
Upvotes: 2
Reputation: 23
<tr mat-header-row *matHeaderRowDef="displayedColumns" [ngClass]="{accent:true}">
In case you need to use accent
or primary
or warn
Upvotes: 3
Reputation: 4959
I assume that you want to apply make-gold
class when IsGranted
value is true. If this is the case, try this:
<mat-row *matRowDef="let row; columns: displayedColumns;" [ngClass]="{'make-gold': row.IsGranted }">
See also stackblitz demo.
There is also a shorthand syntax:
<mat-row ... [class.make-gold]='row.IsGranted' [class.another-class]="true">
Upvotes: 76