带有验证错误的 Angular6 Material 自定义表单字段控件(mat-error) [英] Angular6 Material custom form field control with validation errors (mat-error)
问题描述
如何制作 Material 自定义表单域控件(像这个) 来支持表单验证并使用 mat-error 显示它们?我知道常规 matInput 指令使用 ErrorStateMatcher (doc) 但我不明白如何将其与自定义表单字段链接.
How to make a Material custom form field control (like this one) to support form validation and display them with mat-error? I understand that the regular matInput directive uses ErrorStateMatcher (doc) but I don't understand how I can link it with a custom form field.
推荐答案
通过查看 Material2 中的一些现有组件 (https://github.com/angular/components/blob/master/src/material/select/select.ts),我找到了一个解决方案.我按照这个例子创建了一个基类
By looking at some existing component from Material2 (https://github.com/angular/components/blob/master/src/material/select/select.ts), I found a solution. I created a base class following this example
export const _MatSelectMixinBase:
CanDisableCtor &
HasTabIndexCtor &
CanDisableRippleCtor &
CanUpdateErrorStateCtor &
typeof MatSelectBase =
mixinDisableRipple(mixinTabIndex(mixinDisabled(mixinErrorState(MatSelectBase))));
我不得不从 Material 存储库中复制一些类型,例如 CanUpdateErrorStateCtor.
I had to copy from the Material repo some types like CanUpdateErrorStateCtor.
然后更新我的构造函数以注入 ErrorStateMatcher,最后在 ngDoCheck 中执行以下操作:
Then update my constructor to inject a ErrorStateMatcher and finally in ngDoCheck, do this:
ngDoCheck() {
if (this.ngControl) {
this.updateErrorState();
}
}
这篇关于带有验证错误的 Angular6 Material 自定义表单字段控件(mat-error)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!