首页 > 解决方案 > Angular Materials - Mat-Select 更改选定值颜色

问题描述

我在我的项目中使用 Angular Material 8.2.3,我正在尝试更改 Mat-Select 组件(即下拉菜单)的选定值颜色,如下所示。

垫选择

在 chrome 检查器中,我可以看到字体颜色由类 .mat-select-value 定义

垫选择值

但是,当我尝试使用类选择器更改颜色时,什么也没有发生。

有没有办法改变选定的值颜色?我在页面上有其他菜单下拉菜单,所以它必须限制在这个组件中。提前谢谢了。

我的代码如下。

HTML

<mat-select class="custom-color"  [(ngModel)]="value">
    <mat-option>
        Yes
    </mat-option>
    <mat-option>
        No
    </mat-option>
</mat-select>

CSS

尝试1:

.custom-color.mat-select-value{
    color: green !important;
}

尝试2:

.custom-color > .mat-select-value{
    color: green !important;
}

标签: angularangular-materialangular-material-8

解决方案


您应该在选择中添加一个类(就像您已经做过的那样)。

之后,你需要得到你想要去多深的选择器(如果div里面有div的话……)

如果您设置的类与该类在同一个 html 组件中mat-select-value,那么您可以这样做.custom-color.mat-select-value

但是,角度材料样式的工作方式是您无法轻松访问它的类(如果您不使用ng-deep)。

要设置组件样式,您必须执行以下操作:

在你的 scss 组件中创建一个 mixin:

@import '~@angular/material/theming';

// Custom mat-select theme
@mixin mat-select-theme() {
  .custom-color.mat-select-value {
     color: green; // You may need to use important here, but it's just in a few cases
  }
}

之后,在您的主 scss 文件(即 styles.scss)中声明您的 @mixin

@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 'pathToFile.scss';
@include mat-select-theme();

试试看。

材料主题指南以备不时之需:

https://material.angular.io/guide/theming


推荐阅读