为什么在带有自定义全局验证器的角度材料 6 中的 mat-form 字段中未显示 mat-error [英] Why mat-error not get displayed inside mat-form field in angular material 6 withcustom global validators

查看:23
本文介绍了为什么在带有自定义全局验证器的角度材料 6 中的 mat-form 字段中未显示 mat-error的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用有角度的材料 6 ,当在 mat-form-field 之后移动到正确显示的 mat-error 时,我在 mat-form-field 内有一个 vaidation 不显示 mat-error.

i am using angular material 6 ,i have a vaidation inside mat-form-field mat-error is not displayed , when move after mat-form-field to the mat-error which is displaying properly.

不工作的代码:

 <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>

有人解释了为什么在该控件中不起作用.

Some one explain why which is not working inside that control.

现场演示:stackblitz

推荐答案

是的,mat-error 默认不显示.它仅在输入被 touched 时显示.

Yes, mat-error does not show up by default. It only shows when the input is touched.

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

But, luckily you can override this behavior using errorStateMatcher input property, bound to mat-input element.

添加此功能的拉取请求.

用法:

<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.

So you have to implement ErrorStateMatcher in your code this way.

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" 的值>

And in your component add a new object matcher for ErrorStateMatcher class, which will act as a value to [errorStateMatcher]="matcher"

matcher = new MyErrorStateMatcher();

我还在您的分叉 堆叠闪电战

建议:

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

You need not provide a ngIf condition for mat-error specifying your formControlName. It will be automatically considered based on the mat-form-field in which it is present.

这篇关于为什么在带有自定义全局验证器的角度材料 6 中的 mat-form 字段中未显示 mat-error的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆