Change row color in Angular Material table

Issue

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:
enter image description here

What I need is to change the background color of the whole row. Not just the cell. Thank you.

Solution

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.

EDIT

There is also a shorthand syntax:

<mat-row ... [class.make-gold]='row.IsGranted' [class.another-class]="true">

Answered By – leopal

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.