Angular 5 Material禁用状态下mat-select选中文本颜色修改方法
修改Angular 5 Material mat-select禁用状态选中文本样式的方案
要搞定这个需求其实很简单,核心就是定位到mat-select禁用状态下包裹选中文本的元素,然后覆盖它的默认颜色样式。下面给你两种实用的方案:
方案一:组件内穿透样式(推荐,不影响全局)
因为Angular默认的视图封装会隔离组件样式,所以需要用::ng-deep来穿透到Material组件的内部DOM结构。在你的组件SCSS文件里添加以下代码:
/* 让启用和禁用状态下的选中文本都显示深蓝色 */ ::ng-deep .mat-select-value-text { color: #003399 !important; /* 这里的颜色值可以根据你的需求调整 */ } /* 如果只需要修改禁用状态的样式,就只保留下面这段 */ ::ng-deep .mat-select-disabled .mat-select-value-text { color: #003399 !important; }
说明:
.mat-select-value-text是Material用来包裹选中值文本的span元素类名.mat-select-disabled是mat-select处于禁用状态时会自动添加的类!important用来确保你的样式优先级高于Material的默认样式,避免被覆盖
方案二:全局样式修改
如果你希望这个样式应用到项目中所有的mat-select组件,可以直接在全局的styles.scss(或styles.css)文件里添加代码:
/* 全局生效的样式 */ .mat-select-value-text { color: #003399; } .mat-select-disabled .mat-select-value-text { color: #003399; }
这种方式不需要::ng-deep,因为全局样式会作用于整个应用的DOM结构。
额外提示
- 如果你担心样式污染其他组件,可以给你的mat-select所在的组件添加一个自定义类,然后更精准地定位:
然后在模板里给mat-form-field加上这个类:::ng-deep .custom-select-container .mat-select-disabled .mat-select-value-text { color: #003399 !important; }<mat-form-field class="custom-select-container"> <mat-select placeholder="Select a Product" [(ngModel)]="selected" [disabled]="isDisabled"> <mat-option *ngFor="let prod of products" [value]="prod.productID"> {{ prod.key }} </mat-option> </mat-select> </mat-form-field> - 颜色值可以用十六进制、RGB、RGBA或者颜色名称,比如
darkblue也是可以的。
内容的提问来源于stack exchange,提问作者tazza
相关产品推荐
相关产品推荐

