在 Angular Material 中,MatFormField 是用来包装表单控件的容器组件。当使用该组件时,可能会遇到 errorstate 属性未定义的问题。
要解决这个问题,可以在使用 MatFormField 组件时,同时使用 MatInput 组件,并在 MatInput 中设置下面这行代码:
[errorStateMatcher]="matcher"
然后再在组件中定义一个 errorStateMatcher:
import { FormControl, FormGroupDirective, NgForm } from '@angular/forms'; import { ErrorStateMatcher } from '@angular/material/core';
export class MyErrorStateMatcher implements ErrorStateMatcher { isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean { const isSubmitted = form && form.submitted; return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted)); } }
最后,将 matcher 变量实例化为这个定义的 MyErrorStateMatcher 类,并将其注入到组件的构造函数中:
export class MyComponent { ... matcher = new MyErrorStateMatcher(); ... }
这样就能使用 MatFormField 和 MatInput 组件,同时避免 errorstate 属性未定义的问题了。