如何更改特定角度材料选项卡的背景颜色?

时间:2019-01-30 07:15:18

标签: html css angular angular-material

我有一个使用角材7的垫选项卡的组件。

我想根据我的打字稿变量的布尔值更改标签的背景颜色。

问题是我只能使用

在所有选项卡上应用CSS
.mat-tab-label {
  background-color: red;
}

如何创建可在特定标签上应用的CSS类。

我有一个标准组件。我尝试使用封装:ViewEncapsulation.None,但这仅允许我如上所述更改所有选项卡。

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 个答案:

答案 0 :(得分:2)

您可能不想设置encapsulation: ViewEncapsulation.None,这会使该组件的样式也适用于所有其他组件。

您可以像这样在styles.scss中为标签设置颜色:

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

答案 1 :(得分:1)

编辑: 如果要更改单个选项卡,则可以使用aria-label输入参数。

您必须添加

encapsulation: ViewEncapsulation.None

并使用特定的CSS选择器,如下所示:

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

您可以找到示例here

如果要使用所有标签:

您有专用的API。

只需像这样使用backgroundColor属性:

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

您可以找到完整的示例here

答案 2 :(得分:0)

如果您不想使用封装:ViewEncapsulation.None,因为它会影响应用于应用程序中其他组件的 css 并且想要定位单个或特定选项卡,那么您可以执行以下操作

<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 具有如下标签

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

确保在 style.scss 或 style.css 中添加以下内容

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

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