对于 Angular 9 mat-tables,有没有办法在一个地方为一行设置 CSS 颜色?

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

在我的 mat-table (Angular 9) 中,我想要一个函数来确定每一行的 CSS class ...

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

classes 相当简单,通常只包括设置颜色 ...

.hot {
        color: red !important;
}

我像这样为行配置函数...

<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>

但是,我注意到 mat-table,mat-cell 定义了它自己的“颜色”属性。覆盖它的一种方法是为每个 "

[ngClass]="getCSSClass(item)"

但这似乎很浪费,尤其是对于有很多列的 tables。我将不得不为每个 ng-container 重复硬编码这个逻辑,当它基本上为所有容器做同样的事情时。有没有更有效的方法来覆盖整行的 mat-cell 颜色属性?

你只需要添加 mat-cell class as sub class of hot class 因为 mat-cell class 默认有 color风格

Material风格

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

你需要添加

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

与其只返回一个字符串,不如尝试以这种格式返回一个对象 - { 'classname': true }

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

如果直接使用 class 属性,它应该可以工作,即使没有 !important 语句。

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

这是一个有效的 StackBlitz