为什么mat-error不会显示在带有自定义全局验证器的角度材质6中的mat-form字段内

前端之家收集整理的这篇文章主要介绍了为什么mat-error不会显示在带有自定义全局验证器的角度材质6中的mat-form字段内前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用角度材料6,我在mat-form-field mat-error中显示错误,当在mat-form-field之后移动到正确显示的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>

有人解释了为什么不在该控制范围内工作.

现场演示:
stackblitz

解决方法

是的,默认情况下不会显示mat-error.它仅显示触摸输入的时间.

但是,幸运的是,您可以使用绑定到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类添加一个新的对象匹配器,它将作为[errorStateMatcher] =“matcher”的值

matcher = new MyErrorStateMatcher();

我还在你的分叉stackblitz添加了相同的代码

建议:

您无需为指定formControlName的mat-error提供ngIf条件.它将根据其所在的mat-form字段自动考虑.

猜你在找的Angularjs相关文章