在我的 Angular 4 应用程序中,我有一个如下所示的自定义表单验证器:
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function myCustomValidator(myCustomArg: string): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (control.value) {
// do some checks with control.value and myCustomArg
// return error if needed
}
// return null otherwise
control.setErrors(null);
return null;
};
}
但是当我尝试以我的一种反应形式使用它时:
ngOnInit() {
this.form = new FormGroup({
'myControl': new FormControl(null, [ myCustomValidator(...) ]),
// ...
});
}
我收到几个错误:
错误类型错误:无法在 FormControl.webpackJsonp.../../../forms/@angular/forms.es5.js.AbstractControl._updateControlsErrors (forms.es5.js:2836) 处读取未定义的属性“发射” .webpackJsonp.../../../forms/@angular/forms.es5.js.AbstractControl.setErrors (forms.es5.js:2772) 在 forms.es5 的 file-extension.validator.ts:17。 js:506 at Array.map () at _executeValidators (forms.es5.js:506) at FormControl.validator (forms.es5.js:462) at FormControl.webpackJsonp.../../../forms/@ angular/forms.es5.js.AbstractControl._runValidator (forms.es5.js:2720) 在 FormControl.webpackJsonp.../../../forms/@angular/forms.es5.js.AbstractControl.updateValueAndValidity (forms .es5.js:2688) 在新的 FormControl (forms.es5.js:3011)
ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 0, nodeDef: {…}, elDef: {…}, elView: {…}}
ERROR Error: formGroup expects a FormGroup instance. Please pass one in.
But unfortunately they are not very helpful.