如何在不设置内置错误的情况下触发mat-date-range-input在mat-form-field中显示mat-error? [英] How to trigger the display of mat-error in a mat-form-field for a mat-date-range-input without setting the built-in errors?

查看:33
本文介绍了如何在不设置内置错误的情况下触发mat-date-range-input在mat-form-field中显示mat-error?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据问题,我有一个日期范围选择器,其中开始 end 日期是 mat-form-field 的一部分.我想执行自定义验证(例如,以确保 start end 之间的绝对差不超过15天)并显示 mat-error位于 mat-form-field 中的,通知用户有关此问题的信息.

As per the question, I have a date range picker with start and end dates as part of a mat-form-field. I want to perform a custom validation (for example, to ensure the absolute difference between start and end is not longer than 15 days) and display a mat-error inside the mat-form-field informing the user about the issue.

我还希望有多个这样的验证器和错误消息.错误是在表单组上正确设置的,但由于表单字段未将这些特定错误标识为该字段的无效"部分,因此不会显示错误.错误集.我通过在开始或结束输入字段上设置 matStartDateInvalid matEndDateInvalid 错误来解决该问题,但这并不是我可以接受的.

I also want to have multiple such validators and error messages. The errors are set on the form group correctly, but they are not displayed since the form field does not identify those specific errors as part of the field's "invalidating" set of errors. I got it to work by doing a nasty workaround setting the matStartDateInvalid or matEndDateInvalid errors on the start or end input fields, but this just is not something I'm okay with.

这是一个突出问题的堆栈闪电:堆栈闪电

Here's a stackblitz highlighting the issue: Stackblitz

如何正确执行此操作?

推荐答案

我明白了!

关键是使用自定义ErrorStateMatcher.如果您定义类似

The key is use a custom ErrorStateMatcher. If you defined some like

export class RangeStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const isSubmitted = form && form.submitted;
    return !!(control && form && form.invalid && (control.dirty || control.touched || isSubmitted));
  }
}

我们可以将errorStateMatcher分配给该函数.看到此RangeStateMAtcher表示该控件是否有效(如果表单有效或无效)

We can asign the errorStateMatcher to this function. See that this RangeStateMAtcher implied that the control is valid or not if the form is valid or not

问题是我不能输入.html

The problem is that I can not put in .html

 <!--this give ERRROR-->
<input matEndDate [errorStateMatcher]="matcher" formControlName="end" 
       [placeholder]="'end'">

因此,我们需要使用ViewChild(我喜欢使用模板引用变量)

So, we need use a ViewChild (I like use a template reference variable)

  @ViewChild('end',{read: MatEndDate,static:true}) endControl: MatEndDate<any>
  //and in ngOnInit

  ngOnInit() {
    ....
    this.endControl.errorStateMatcher=new RangeStateMatcher()
  }

  //in .html 
  <input #end  matEndDate formControlName="end" [placeholder]="'end'">

请参见 stackbliz

这篇关于如何在不设置内置错误的情况下触发mat-date-range-input在mat-form-field中显示mat-error?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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