角度反应形式和自定义验证器错误

时间:2017-10-21 10:18:13

标签: angular typescript angular-reactive-forms angular-forms angular-validation

在我的Angular 4应用中,我有一个custom form validator,如下所示:

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;
  };
}

但是当我尝试在我的reactive forms之一中使用它时

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

我收到了几个错误:

  

ERROR TypeError:无法读取属性' emit'未定义的       在FormControl.webpackJsonp ... / .. / .. / forms/@angular/forms.es5.js.AbstractControl._updateControlsErrors(forms.es5.js:2836)       在FormControl.webpackJsonp ... / .. / .. / forms/@angular/forms.es5.js.AbstractControl.setErrors(forms.es5.js:2772)       在file-extension.validator.ts:17       at forms.es5.js:506       在Array.map()       at _executeValidators(forms.es5.js:506)       在FormControl.validator(forms.es5.js:462)       在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:{...}}

  

错误错误:formGroup需要一个FormGroup实例。请通过一个。

但遗憾的是他们并没有太大帮助。

1 个答案:

答案 0 :(得分:1)

该问题与验证者分配到该字段的方式有关。

事实上,验证者正试图访问控件的值control.value

但是当调用验证器工厂函数时,控件还不存在:

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

因此,为了解决问题,只需首先创建表单,然后然后分配验证程序:

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(...),
  ]);
}