2

在我的 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.

4

1 回答 1

4

The issue is related with the way the validator is assigned to the field.

In fact, the validator is trying to access to the control's value control.value.

But when the validator factory function is called, the control doesn't exist yet:

this.form = new FormGroup({
  'myControl': new FormControl(null, [ myCustomValidator(...) ]),
  // ...
});

So in order to solve the issue, just create the form first and then assign the validator:

ngOnInit() {
   // first create the form with its controls
  this.form = new FormGroup({
    'myControl': new FormControl(null),
    // ...
  });

  // then assign the custom validator
  this.form.get('myControl').setValidators([
    myCustomValidator(...),
  ]);
}
于 2017-10-21T10:18:13.360 回答