【问题标题】:How to change background color of specific angular material tabs?如何更改特定角度材质选项卡的背景颜色?
【发布时间】:2019-06-23 09:52:10
【问题描述】:

我有一个使用 Angular Material 7 中的 mat tab 的组件。

我想根据我的 typescript 变量的布尔值更改选项卡的背景颜色。

问题是我只能在所有标签上应用 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>

【问题讨论】:

标签: html css angular angular-material


【解决方案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

【讨论】:

  • 我想改变一个标签的颜色 - 而不是整个标签组的颜色。我该如何管理?
  • 像这样使用 aria-label 会破坏可访问性,因为屏幕阅读器会说“backgroundColorToggle.value”而不是标签标签。
【解决方案2】:

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

相反,您可以像这样在styles.scss 中设置标签的颜色:

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

【讨论】:

    【解决方案3】:

    如果您不想使用封装: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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多