0
votes

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?

3
Did you try to add "!important"? - oz1985oz
seems some css overiding in your code otherwise the logic which you have used for mat-row calls should works fine and change the entire row background. <mat-row *matRowDef="let row; columns: displayedColumns;" [ngClass]="getRowClass(row)"></mat-row> - Shivansh Seth
@oz1985oz, yes tried !important. Updated my question to include it. Still no difference. - satish
Can you create a stackblitz example? I don't really understand your problem stackblitz.com/edit/angular-rph4cs - David

3 Answers

1
votes

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
}
1
votes

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 };
}
0
votes

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