Angular 11中为mat-horizontal-stepper自定义类样式的问题
为Angular 11的Mat水平步进器自定义单独样式
问题场景
在Angular 11环境中,两个独立组件各包含一个mat-horizontal-stepper,需要通过自定义类分别控制不同步进器的选中/未选中步骤颜色。目前全局样式可作用于所有步进器,但无法为单个步进器应用自定义类样式。
组件1代码
<mat-horizontal-stepper class="greenStepper"> <mat-step><ng-template matStepLabel>1</ng-template>stuff</mat-step> <mat-step><ng-template matStepLabel>2</ng-template>stuff</mat-step> <mat-step><ng-template matStepLabel>3</ng-template>stuff</mat-step> </mat-horizontal-stepper>
组件2代码
<mat-horizontal-stepper class="blueStepper"> <mat-step><ng-template matStepLabel>A</ng-template>stuff</mat-step> <mat-step><ng-template matStepLabel>B</ng-template>stuff</mat-step> <mat-step><ng-template matStepLabel>C</ng-template>stuff</mat-step> </mat-horizontal-stepper>
当前全局样式(作用于所有步进器)
.mat-step-header[aria-selected="true"] { background-color: blue !important; } .mat-step-header[aria-selected="false"] { background-color: white !important; }
错误的期望样式写法
之前尝试的写法无法生效,核心问题是选择器层级错误:
.mat-step-header[aria-selected="true"].blueStepper { background-color: blue!important; } .mat-step-header[aria-selected="true"].greenStepper { background-color: green !important; }
解决方法
自定义类greenStepper/blueStepper是添加在mat-horizontal-stepper元素上,而.mat-step-header是它的子元素,需要使用后代选择器来匹配父容器下的子元素:
正确的全局样式写法
/* 蓝色步进器样式 */ .blueStepper .mat-step-header[aria-selected="true"] { background-color: blue !important; } .blueStepper .mat-step-header[aria-selected="false"] { background-color: #f0f0f0 !important; /* 自定义未选中状态颜色 */ } /* 绿色步进器样式 */ .greenStepper .mat-step-header[aria-selected="true"] { background-color: green !important; } .greenStepper .mat-step-header[aria-selected="false"] { background-color: #e8f5e9 !important; /* 自定义未选中状态颜色 */ }
说明
- 选择器
.blueStepper .mat-step-header表示:选中拥有blueStepper类的容器下的所有.mat-step-header子元素 - 保留
!important是为了覆盖Material组件的默认内联样式,若样式权重足够也可尝试移除
内容的提问来源于stack exchange,提问作者A. Patterson
相关产品推荐
相关产品推荐

