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

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

问题描述

我正在使用角材6,当在垫形场之后移动到正确显示的垫形误差时,我没有显示垫形场内的错误。

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 默认情况下不显示。仅在输入被触摸时显示。

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

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

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

拉动请求

The pull request in which this feature was added.

用法:

<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);
  }
}

然后在组件中添加新对象 matcher 用于 ErrorStateMatcher 类,它将作为 [errorStateMatcher] = matcher 的值code>

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

matcher = new MyErrorStateMatcher();

我还为您的 stackblitz

建议

您无需为 mat提供 ngIf 条件-错误,指定您的 formControlName 。系统会根据其所在的 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的垫形字段内未显示垫错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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