表格标题背景颜色动态变化 - Angular 材质

Sat*_*hia 0 css html-table angular-material angular

我按照这个例子来实现角度材料表。

https://stackblitz.com/angular/jejeknenmgr?file=src%2Fapp%2Ftable-basic-example.ts

在这里,我使用下面的 CSS 代码更改了标题颜色。

.mat-header-cell {
    background: red;
}
Run Code Online (Sandbox Code Playgroud)

我想从组件传递标题颜色而不是静态 CSS 方式。有没有办法动态改变标题颜色?

Arm*_*yan 5

一种方法是使用Css Var并在组件中以编程方式更改变量值。

CSS

.mat-header-cell {
    background: var(--background-color)
}
Run Code Online (Sandbox Code Playgroud)

成分

export class AppComponent {
  constructor()

  changeColor() {
    // set new color here
    document.documentElement.style.setProperty(`--background-color`, 'red');
  }
}
Run Code Online (Sandbox Code Playgroud)

因此,当您更改 css 中的变量时,浏览器将更改.mat-header-cell类中的值

background-color另一种方法是在每个项目上使用内联样式属性mat-header-cell

在 HTML 中

  <ng-container matColumnDef="position">
    <th mat-header-cell *matHeaderCellDef [style.background-color]="color"> No. </th>
    <td mat-cell *matCellDef="let element"> {{element.position}} </td>
  </ng-container>

Run Code Online (Sandbox Code Playgroud)

在组件中

export class TableBasicExample {
  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = ELEMENT_DATA;
  color = 'green'

 changeColor() {
   this.color = 'red';
 }

}

Run Code Online (Sandbox Code Playgroud)

例子

  • 谢谢,这就是我所期望的。 (2认同)