我正在使用 Angular Material 6,我在 mat-form-field 中有一个验证,当在 mat-form-field 之后移动到正确显示的 mat-error 时,mat-error 未显示。
无效代码:
<mat-form-field>
<input matInput type="time" formControlName="ToTime"/> <mat-error *ngIf="DaterForm.get('ToTime').hasError('InValidToTime')">FromTime Should be less than ToTime if choose a same date</mat-error>
</mat-form-field>
工作正常:
<input matInput type="time" formControlName="ToTime"/> </mat-form-field>
<mat-error *ngIf="DaterForm.get('ToTime').hasError('InValidToTime')">FromTime Should be less than ToTime if choose a same date</mat-error>
有人解释了为什么 which 在该控件内不起作用。
现场演示: stackblitz
最佳答案
是的,mat-error
默认不显示。它仅在输入被触摸
时显示。
但是,幸运的是,您可以使用绑定(bind)到 mat-input
元素的 errorStateMatcher
输入属性覆盖此行为。
pull request其中添加了此功能。
用法:
<mat-form-field>
<input matInput [errorStateMatcher]="matcher" [matDatepicker]="picker" placeholder="Choose a Start date"
formControlName="FromDate"
[min]="minFromDate"
[max]="maxToDate" >
<mat-datepicker-toggle matSuffix [for]="picker" ></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
<mat-error >Please provide a valid Fromdate</mat-error>
</mat-form-field>
所以你必须以这种方式在你的代码中实现 ErrorStateMatcher
。
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const isSubmitted = form && form.submitted;
return (control && control.invalid);
}
}
然后在您的组件中为 ErrorStateMatcher
类添加一个新对象 matcher
,它将充当 [errorStateMatcher]="matcher"
matcher = new MyErrorStateMatcher();
我还在你的 fork stackblitz 中添加了相同的代码
建议:
您无需为指定formControlName
的mat-error
提供ngIf
条件。系统会根据它所在的 mat-form-field
自动考虑它。
关于angular - 为什么 mat-error 不会在带有自定义全局验证器的 Angular Material 6 中的 mat-form 字段中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51456487/