[英]How do I use CSS to style Angular Material tabs?
我对 Angular 很陌生。 我最近在我的应用项目中添加了 Angular 材料选项卡,类似于下面的一个。
<mat-tab-group>
<mat-tab label="First" class="firstTab"> Content 1 </mat-tab>
<mat-tab label="Second" class="secondTab"> Content 2 </mat-tab>
<mat-tab label="Third" class="thirdTab"> Content 3 </mat-tab>
</mat-tab-group>
在我的应用程序中,有时我需要将某些选项卡引起用户的注意。 我正在考虑的方法是通过赋予以下特性来突出显示感兴趣的选项卡:
.highLightTab{
border-width: 9px;
border-style: solid;
border-color: orange;
}
实现上述目标的传统方法是通过
$(".secondTab").addClass("highLightTab");
然而,事实证明这是不可能实现的,因为我无法为运行时生成的任何 Mat-X 元素定制 CSS 类/CSS 样式。
谁能告诉我如何实现这一目标?
要将自定义 class 添加到材质选项卡,您必须使用ng-template
语法:
<mat-tab-group>
<mat-tab>
<ng-template mat-tab-label>
<span class="my-custom-class">Security</span>
</ng-template>
Content 1
</mat-tab>
<mat-tab label="Second" class="secondTab"> Content 2 </mat-tab>
<mat-tab class="my-custom-class" label="Third" class="thirdTab"> Content 3 </mat-tab>
</mat-tab-group>
有了这个,您可以像往常一样my-custom-class
样式:
.my-custom-class {
border-width: 9px;
border-style: solid;
border-color: red;
}
您还可以使用::ng-deep
伪元素设置默认材质类的样式。
:host ::ng-deep .mat-tab-label-active {
border-width: 9px;
border-style: solid;
border-color: orange;
}
:host
是可选的,它将 styles 的范围限定为当前组件中的选项卡。
附件是stackblitz演示。
我不推荐使用 ng-deep,因为它已被弃用:
https://angular.io/guide/component-styles#deprecated-deep--and-ng-deep
相反,您应该将其设置为 angular 材料文档:
https://material.angular.io/guide/theming
由于您可能会有很多自定义 styles 用于您的材料组件,因此这是一种更好的方法,您可以根据需要将所有材料自定义 styles 集中在一个 scss 文件中。
实现示例(未经测试,但应该可以):
我的自定义元素.scss
@import '~@angular/material/theming';
@mixin custom-tabs-theme() {
.mat-tab-label-active {
border-width: 9px;
border-style: solid;
border-color: orange;
}
}
全球材料主题.scss
@import '~@angular/material/theming';
// Plus imports for other components in your app.
// Include the common styles for Angular Material. We include this here so that you only
// have to load a single css file for Angular Material in your app.
// Be sure that you only ever include this mixin once!
@include mat-core();
@import './material/my-custom-elements.scss';
@include custom-tabs-theme();
angular.json
...
"styles": ["src/styles.scss", "src/app/global-material-theme.scss"]
...
注意:您可以通过这种方式编辑任何材料 css class。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.