如何移除Angular Material mat-form-field初始、悬停及聚焦背景色?
修改Angular Material mat-form-field 全状态背景色为白色(通用方案)
一、通用CSS方案(全局styles.scss)
直接使用Angular Material提供的通用类选择器,覆盖所有状态下的filled输入框背景色,无需依赖动态生成的ng-tns-xxx类:
/* 默认状态 */ .mat-mdc-form-field.mat-mdc-form-field-type-mat-input:not(.mat-form-field-disabled) .mdc-text-field--filled { background-color: white; } /* 悬停状态 */ .mat-mdc-form-field.mat-mdc-form-field-type-mat-input:not(.mat-form-field-disabled):hover .mdc-text-field--filled { background-color: white; } /* 聚焦状态 */ .mat-mdc-form-field.mat-mdc-form-field-type-mat-input:not(.mat-form-field-disabled).mat-focused .mdc-text-field--filled { background-color: white; } /* 错误状态(可选) */ .mat-mdc-form-field.mat-mdc-form-field-type-mat-input.mat-form-field-invalid:not(.mat-form-field-disabled) .mdc-text-field--filled { background-color: white; }
为什么不用ng-tns-xxx类?
这类类是Angular视图封装机制动态生成的唯一标识符,每次编译、组件复用或部署后都会变化,硬编码会导致新添加的输入框无法生效,且代码维护性极差,完全不具备通用性。
二、推荐方案:使用Angular Material自定义主题
通过自定义主题变量统一配置,更符合Material Design的主题体系,无需额外编写覆盖样式:
在全局styles.scss中修改主题定义:
@use '@angular/material' as mat; // 定义基础主题 $custom-theme: mat.define-light-theme(( color: ( primary: mat.define-palette(mat.$indigo-palette), accent: mat.define-palette(mat.$pink-palette), warn: mat.define-palette(mat.$red-palette), ), typography: mat.define-typography-config(), density: 0, )); // 自定义filled输入框的背景色(所有状态统一为白色) $filled-text-bg: white; // 注入基础主题 @include mat.core-theme($custom-theme); @include mat.all-component-themes($custom-theme); // 覆盖filled输入框的主题变量 @include mat.filled-text-field-theme($custom-theme, ( container-color: $filled-text-bg, hover-container-color: $filled-text-bg, focused-container-color: $filled-text-bg, invalid-container-color: $filled-text-bg, ));
三、组件内局部修改方案
如果仅需在特定组件内生效,可使用以下两种方式:
方式1:使用::ng-deep穿透视图封装
在组件的.scss文件中添加:
:host ::ng-deep .mat-mdc-form-field.mat-mdc-form-field-type-mat-input:not(.mat-form-field-disabled) .mdc-text-field--filled { background-color: white; } :host ::ng-deep .mat-mdc-form-field.mat-mdc-form-field-type-mat-input:not(.mat-form-field-disabled):hover .mdc-text-field--filled { background-color: white; } :host ::ng-deep .mat-mdc-form-field.mat-mdc-form-field-type-mat-input:not(.mat-form-field-disabled).mat-focused .mdc-text-field--filled { background-color: white; }
方式2:关闭组件视图封装
在组件类中关闭视图封装,然后直接写通用选择器:
import { Component, ViewEncapsulation } from '@angular/core'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html', styleUrls: ['./your-component.component.scss'], encapsulation: ViewEncapsulation.None // 关闭视图封装 }) export class YourComponentComponent { }
之后在组件的.scss中直接使用全局方案的CSS代码即可,注意避免样式污染其他组件。
内容的提问来源于stack exchange,提问作者he1dj
相关产品推荐
相关产品推荐

