2
votes

I have a component using mat tab from angular material 7.

I want to change the background color of my tabs depending on a boolean value of my typescript variable.

The problem is that I can only apply the CSS on all tabs with

.mat-tab-label {
  background-color: red;
}

How to create a CSS class which I can apply on a specific tab.

I have a standard component. I tried using encapsulation: ViewEncapsulation.None but this only allowed me to change all tabs as mentioned above.

HTML:

<mat-tab-group mat-align-tabs="center" dynamicHeight="true">
  <mat-tab label="tab1">
    Hello
  </mat-tab>
  <mat-tab label="tab2">
    Hello2
  </mat-tab>
</mat-tab-group>
3
you want something like this stackblitz.com/edit/… - Abhishek

3 Answers

3
votes

Edited: If you want to change a single tab you can use the aria-label input parameter.

You'll have to add the

encapsulation: ViewEncapsulation.None

And use a specific css selectors like so:

HTML:

<mat-tab-group [color]="colorToggle.value" [backgroundColor]="backgroundColorToggle.value">
  <mat-tab label="First" [aria-label]=backgroundColorToggle.value> Content 1 </mat-tab>
  <mat-tab label="Second"> Content 2 </mat-tab>
  <mat-tab label="Third"> Content 3 </mat-tab>
</mat-tab-group>

CSS:

[aria-label=primary] {
  background-color: blue;
}

[aria-label=accent] {
  background-color: aqua;
}

You can find example here

If you want for all tabs:

You have a dedicated API for it.

Just use the backgroundColor property like so:

<mat-tab-group [color]="colorToggle.value" [backgroundColor]="backgroundColorToggle.value">

You can find the full example here

3
votes

You might not want to set encapsulation: ViewEncapsulation.None, this will make the styling for this component be applied to all other components too.

Instead you can set the color for the tab in your styles.scss like this:

.mat-tab-header{
    background-color: #424242;
}
0
votes

If you don't want to use encapsulation: ViewEncapsulation.None as it effects to the css applied to other components in the app and want to target a single or specific tab then you can do something like below

<mat-tab-group>
  <mat-tab label="First" *ngFor="let tab of tabs;" [aria-label]="tab.bgColorClass"> {{tab.content}} </mat-tab>
</mat-tab-group>

your.component.ts having the tabs like below

export class YourComponent implements OnInit {
    tabs = [
        {
            "bgColorClass": "primary",
            "content": "Tab Content ... "
        },
        {
            "bgColorClass": "secondary",
            "content": "Tab Content..."
        }
    ];
}

make sure to add the following in your style.scss or style.css

[aria-label="primary"] {
  background-color: #2ecc71;
}

[aria-label="secondary"] {
  background-color: #e53935;
}