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?
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';
}
}