2

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?

satish
  • 703
  • 5
  • 23
  • 52

3 Answers3

3

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
}
Mehdi Shakeri
  • 584
  • 3
  • 11
2

If you use the class attribute directly it should work, even without the !important statements.

<mat-row *matRowDef="let row; columns: displayedColumns;" [class]="getRowClass(row)"></mat-row>

Here is a working StackBlitz

m4n0
  • 29,823
  • 27
  • 76
  • 89
1

Instead of just returning a string try returning an object in this format - { 'classname': true }

getRowClass(item: Item): object {
  let class_ = "";
  if (...condition1...) {
      ...
  } else {
    class_ = 'warm';
  }
  return { class_: true };
}
Luke Weaver
  • 271
  • 1
  • 9