Sathiamoorthy
Sathiamoorthy

Reputation: 11630

table header background color change dynamically - Angular material

I have followed this example to implement the angular material table.

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

Here I changed the heading color using the below CSS code.

.mat-header-cell {
    background: red;
}

I want to pass the heading color from the component instead of the static CSS way. Is there any way to change the heading color dynamically?

Upvotes: 2

Views: 21298

Answers (2)

fbraun
fbraun

Reputation: 1

For Angular 18 I recently discovered that the class changed. For anyone who's interested or looking for an answer!

In your case it would be:

.mat-mdc-cell, .mat-mdc-header-cell { background: var(--background-color) }

Upvotes: 0

Armen Stepanyan
Armen Stepanyan

Reputation: 1846

One of approach is to use Css Var and change variable value programatically in component.

Css

.mat-header-cell {
    background: var(--background-color)
}

Component

export class AppComponent {
  constructor()

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

So when you change variable in css, browser will change value in .mat-header-cell class

Another approach is to use inline style background-color attribute on each mat-header-cell item.

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

In component

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

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

}

Example

Upvotes: 6

Related Questions