You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Material:如何修改选中mat-option的文本颜色

修改Mat-Option选中文本“2020”的颜色

嘿,我来帮你搞定这个Angular Material选中项文本变色的问题~下面给你几种实用的方法,你可以根据需求选:

方法一:全局/组件内统一修改选中文本颜色(简单粗暴)

如果不管选哪个年份,都想统一修改选中后的文本颜色,直接在样式文件里加这段代码就行。如果是组件内样式,记得加::ng-deep来穿透Angular的视图封装:

/* 组件内样式需要加::ng-deep,全局样式可以去掉 */
::ng-deep .mat-select-value-text {
  color: #ff5722; /* 替换成你想要的颜色值 */
}

方法二:仅针对“2020”选项选中时变色(精准控制)

如果只想让选中2020时文本变色,其他年份保持默认,可以这么做:

第一步:给目标mat-option加自定义类

修改你的HTML代码,给2020的选项加个类名:

<mat-form-field appearance="fill" style="width: 100px;">
  <mat-label>Year</mat-label>
  <mat-select formControlName="year">
    <mat-option [value]="2020" class="year-2020"> 2020 </mat-option>
    <mat-option [value]="2021"> 2021 </mat-option>
  </mat-select>
</mat-form-field>

第二步:编写对应样式

在样式文件里添加这段代码,利用:has()伪类判断选中的是带自定义类的选项:

::ng-deep .mat-select-value-text:has(.year-2020.mat-selected) {
  color: #4caf50; /* 选中2020时的颜色 */
}

方法三:结合表单控件动态绑定样式(更灵活)

如果你想通过表单控件的状态来动态控制颜色,可以用Angular的动态类绑定:

第一步:在组件类里获取formControl

假设你的组件里已经有对应的FormControl:

import { FormControl } from '@angular/forms';

// 组件类内定义
yearControl = new FormControl(2020); // 初始值设为2020

第二步:给mat-form-field加动态类

修改HTML,根据formControl的值添加类:

<mat-form-field 
  appearance="fill" 
  style="width: 100px;"
  [class.selected-2020]="yearControl.value === 2020"
>
  <mat-label>Year</mat-label>
  <mat-select [formControl]="yearControl">
    <mat-option [value]="2020"> 2020 </mat-option>
    <mat-option [value]="2021"> 2021 </mat-option>
  </mat-select>
</mat-form-field>

第三步:编写样式

.selected-2020 .mat-select-value-text {
  color: #9c27b0; /* 选中2020时的颜色 */
}

这些方法都能实现你要的效果,选最适合你项目的就行~

内容的提问来源于stack exchange,提问作者Malakmkd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 15:53:15