Angular Material如何修改Mat Select组件下拉选项的字体家族
解决Angular mat-select下拉选项字体样式无法生效问题
问题原因
mat-select的下拉选项面板默认挂载在全局的overlay容器中,不属于当前组件的DOM子树,因此仅在组件样式文件内使用
::ng-deep配合:host无法匹配到面板元素;而ViewEncapsulation.None会取消组件的样式隔离,所有组件样式都会全局生效,自然会引发样式渗透问题。
可行解决方案
方案1:自定义面板类+全局样式(最推荐)
该方案无需修改组件逻辑,无样式渗透风险,适配所有场景
- 第一步:在组件模板的
mat-select标签上添加自定义面板类
<mat-select panelClass="custom-select-font-panel"> <mat-option value="xxx">你出生在哪个城市</mat-option> <!-- 其他选项 --> </mat-select>
- 第二步:在项目全局样式文件(通常是
src/styles.css或styles.scss)中添加对应样式
/* 仅作用于添加了custom-select-font-panel类的mat-select下拉面板 */ .custom-select-font-panel .mat-option { font-family: "你需要的字体", sans-serif; }
方案2:修改面板挂载位置+组件内样式
如果不想将样式写到全局文件,可将下拉面板挂载到当前组件的DOM子树内,再用::ng-deep修改
- 第一步:组件ts文件中修改mat-select的overlay容器绑定
import { Component, ViewChild, ViewContainerRef, AfterViewInit } from '@angular/core'; import { MatSelect } from '@angular/material/select'; @Component({ // 你的原有组件配置 }) export class YourComponent implements AfterViewInit { @ViewChild(MatSelect) private select!: MatSelect; constructor(private viewContainerRef: ViewContainerRef) {} ngAfterViewInit(): void { // 将下拉面板绑定到当前组件的视图容器下 this.select.overlayDir.viewContainerRef = this.viewContainerRef; } }
- 第二步:在组件的css文件中添加样式
/* 仅作用于当前组件内的mat-select选项 */ :host ::ng-deep .mat-option { font-family: "你需要的字体", sans-serif; }
内容的提问来源于stack exchange,提问作者the_overflowing_stack
相关产品推荐
相关产品推荐

