Search code examples
cssangularangular9mat-table

For Angular 9 mat-tables, is there a way to set the CSS color for a row in just a single place?


In my mat-table (Angular 9), I want to have a function that determines the CSS class for each row ...

  getRowClass(item: Item): string {
    let class_ = "";
    if (...condition1...) {
        ...
    } else {
      class_ = 'warm';
    }
    return class_;
  }

The classes are fairly simple, and usually just consist of setting the color ...

.hot {
        color: red !important;
}

I configure the function for the row like so ...

<mat-table #table [dataSource]="dataSource">
    <ng-container matColumnDef="category">
      <mat-header-cell *matHeaderCellDef> category </mat-header-cell>
      <mat-cell *matCellDef="let item">{{ item.category }}</mat-cell>
    </ng-container>

    ...
  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns;" [ngClass]="getRowClass(row)"></mat-row>
</mat-table>

However, I'm noticing with the mat-table, mat-cell defines its own "color" attribute. One way to override it would be for each "<mat-cell *matCellDef" class to define

[ngClass]="getCSSClass(item)"

but this seems wasteful especially for tables that have many columns. I would have to repeatedly hard-code this logic for each ng-container, when it is essentially doing the same thing for all. Is there a more efficient way to override the mat-cell color attribute for an entire row?


Solution

  • you just need to add mat-cell class as sub class of hot class because mat-cell class by default has color style

    Material style

    .mat-cell, .mat-footer-cell {
        color: rgba(0,0,0,.87);
    }
    

    and you need add

    .hot .mat-cell {
      color: blueviolet !important
    }