我正在尝试这样做
@Directive({
selector: '[myVal][myCustomInputToComponent]',
providers: [
{ provide: NG_VALIDATORS, useExisting: forwardRef(() => MyVal), multi: true }
]
})
export class MyVal implements OnInit, Validator {
@Input() input: any;
constructor(private el: ElementRef) {
}
ngOnInit(): void {
console.log('validator input', this.input);
}
validate(): { [key: string]: any } {
console.log('validate', this.input)
return {
validatorName: {
valid: false
}
};
}
}
And validate
方法显然没有被调用。但也许有某种方法可以检测具有有效和无效状态的组件。我们不仅仅使用 FormControls 来与客户交互,不是吗?
卡琳娜,您无法验证任何组件。您可以验证一个特殊的组件:自定义表单控件。在自定义表单控件中,您可以在自定义表单控件内部或外部创建验证器。但这必须实现 ControlValueAccessor。
当然,您可以有一个组件,例如更改输入调用函数,但实际上不是验证
如果您的自定义表单控件在控件内有一个验证器,您的自定义表单控件必须添加为提供程序 NG_VALIDATORS,并且将类似于
@Component({
selector: 'app-custom-form-control',
template: `...
`,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomFormControl),
multi: true
},
{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => CustomFormControl),
multi: true,
}
]
})
export class CustomFormControl implements ControlValueAccessor {
onChange;
onTouched;
constructor(el:ElementRef){}
writeValue(value: any[]|any): void {
...receive a value, make something to show it...
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
}
//A function that, when some happens, send a change
setValue(value: any) {
this.onChange(...)
}
focusOut()
{
this.onTouched()
}
validate(control: AbstractControl): ValidationErrors | null{
..your logic here..
return null
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)