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

Moh*_*hir 8 angular-material2 angular angular6 angular-material-6

我正在使用角度材料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>
Run Code Online (Sandbox Code Playgroud)

工作正常:

 <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>
Run Code Online (Sandbox Code Playgroud)

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

现场演示: stackblitz

Ami*_*ani 9

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

但是,幸运的是,您可以使用errorStateMatcher绑定到mat-input元素的input属性覆盖此行为.

添加此功能的pull请求.

用法:

<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> 
Run Code Online (Sandbox Code Playgroud)

所以你必须以ErrorStateMatcher这种方式在你的代码中实现.

export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const isSubmitted = form && form.submitted;
    return (control && control.invalid);
  }
}
Run Code Online (Sandbox Code Playgroud)

在你的组件中matcherErrorStateMatcher类添加一个新对象,它将作为一个值[errorStateMatcher]="matcher"

matcher = new MyErrorStateMatcher();
Run Code Online (Sandbox Code Playgroud)

我还在你的forked stackblitz中添加了相同的代码

建议:

您无需提供指定您的ngIf条件.它将根据它所在的位置自动考虑.mat-errorformControlNamemat-form-field