2

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?

2
  • P.S. your stackblitz link does not works Commented Feb 8, 2021 at 11:21
  • updated stackblitz link Commented Feb 8, 2021 at 11:30

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

4 Comments

vote up, working. I am looking for some other option.
@Shakthifuture I've editted my answer, check the second approach
Thank you, this is what I have expected.
For newer angular versions the class is .mat-mdc-header-cell.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.