根据问题,我有一个日期范围选择器start
and end
日期作为mat-form-field
。我想执行自定义验证(例如,确保之间的绝对差异start
and end
不超过 15 天)并显示mat-error
在 - 的里面mat-form-field
告知用户该问题。
我还想要多个这样的验证器和错误消息。错误已在表单组上正确设置,但不会显示,因为表单字段不会将这些特定错误识别为字段“无效”错误集的一部分。我通过一个令人讨厌的解决方法设置来让它工作matStartDateInvalid
or matEndDateInvalid
开始或结束输入字段出现错误,但这不是我可以接受的。
这是一个突出显示该问题的 stackblitz:斯塔克闪电战 https://stackblitz.com/edit/angular-ivy-v4wcbq
我怎样才能以正确的方式做到这一点?
我得到它!
关键是使用自定义的ErrorStateMatcher。如果你定义了一些像
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暗示了表单有效与否,控件是否有效
问题是我无法放入 .html
<!--this give ERRROR-->
<input matEndDate [errorStateMatcher]="matcher" formControlName="end"
[placeholder]="'end'">
所以,我们需要使用 ViewChild (我喜欢使用模板引用变量)
@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'">
See the 堆栈闪电战 https://stackblitz.com/edit/angular-ivy-2fk9sx?file=src%2Fapp%2Fapp.component.ts
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)