如何在不设置内置错误的情况下为 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?

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

问题描述

根据问题,我有一个日期范围选择器,其中 startend 日期作为 mat-form-field 的一部分.我想执行自定义验证(例如,确保 startend 之间的绝对差异不超过 15 天)并显示 mat-errormat-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.

我也想要多个这样的验证器和错误消息.错误在表单组上设置正确,但它们没有显示,因为表单域没有将这些特定错误标识为域无效"的一部分.错误集.我通过在开始或结束输入字段上设置 matStartDateInvalidmatEndDateInvalid 错误的一个讨厌的解决方法来让它工作,但这不是我可以接受的.

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.

这是一个突出问题的 stackblitz:Stackblitz

Here's a stackblitz highlighting the issue: Stackblitz

我怎样才能以正确的方式做到这一点?

How can I do this the right way?

推荐答案

我明白了!

关键是使用自定义的 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天全站免登陆