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

Posted

技术标签:

【中文标题】如何更改特定角度材质选项卡的背景颜色?【英文标题】: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>

【问题讨论】:

你想要这样的东西stackblitz.com/edit/… 【参考方案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;

【讨论】:

以上是关于如何更改特定角度材质选项卡的背景颜色?的主要内容,如果未能解决你的问题,请参考以下文章

更改 PYQT4 中选项卡的背景颜色

JQuery Tabs - 在输入条目上更改选项卡的背景颜色

更改角度日期选择器材质组件的颜色

如何在开始滚动和透明后将角度材质工具栏背景颜色更改为白色?

单击选项卡和背景更改(不是选项卡的背景)

如何更改角度材料中选定选项卡的下划线颜色?