Angular Material mat-form-field如何在页面初始加载时显示校验错误提示
核心原因
Angular Material 的 mat-error 默认仅在以下两种场景显示校验错误:
- 表单控件处于
touched状态(被聚焦过再失焦) - 父表单已触发过提交动作
哪怕校验规则本身已经不满足,只要状态不符合就不会显示,这是默认的交互规则。
你之前尝试的ng-model-options是 AngularJS(1.x版本)的语法,Angular 2+ 对应的属性是[ngModelOptions],所以写法不对自然不会生效。
解决方案
方案1:自定义 ErrorStateMatcher(推荐)
Angular Material 提供了 ErrorStateMatcher 配置项,可自定义 mat-error 的显示逻辑,我们可以直接配置为只要校验不通过就显示错误,不受状态限制。
- 首先在组件TS文件中定义自定义匹配器:
import { ErrorStateMatcher } from '@angular/material/core'; import { FormControl, NgForm, FormGroupDirective } from '@angular/forms'; export class AlwaysShowErrorMatcher implements ErrorStateMatcher { isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean { // 只要控件存在且校验不通过,就返回true显示错误 return !!(control && control.invalid); } }
- 在组件类中实例化匹配器:
export class YourComponent { isMandatory = true; // 声明匹配器实例 errorMatcher = new AlwaysShowErrorMatcher(); }
- 模板中给输入框绑定匹配器,同时补全必填的ngModel相关配置(否则表单控件状态无法被识别):
<mat-form-field> <mat-label>输入项</mat-label> <input name="testInput" ngModel [required]="isMandatory" placeholder="Just a placeholder" [errorStateMatcher]="errorMatcher" > <mat-error *ngIf="isMandatory">mandatory field</mat-error> </mat-form-field>
方案2:初始化时手动标记控件为touched
如果不想修改默认匹配规则,也可以在页面初始化完成后,手动把对应表单控件标记为touched状态,触发错误提示显示:
- 模板中给input添加模板引用:
<input #myInput="ngModel" name="testInput" ngModel [required]="isMandatory" placeholder="Just a placeholder" >
- 组件TS中获取控件实例,初始化时标记状态:
import { ViewChild, NgModel, AfterViewInit } from '@angular/core'; export class YourComponent implements AfterViewInit { isMandatory = true; @ViewChild('myInput') myInput: NgModel; ngAfterViewInit() { if (this.isMandatory) { // 手动标记为已触碰,触发错误显示 this.myInput.control.markAsTouched(); } } }
内容的提问来源于stack exchange,提问作者Billy
相关产品推荐
相关产品推荐

