【问题标题】:Angular reactive forms and custom validator error角度反应形式和自定义验证器错误
【发布时间】:2018-04-02 09:37:07
【问题描述】:

在我的 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(...) ]),
      // ...
    });
  }

我收到几个错误:

错误类型错误:无法读取未定义的属性“发射” 在 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) 在文件扩展名.validator.ts:17 在 forms.es5.js:506 在 Array.map() 在 _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 实例。请传一个。

但不幸的是,它们并不是很有帮助。

【问题讨论】:

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


    【解决方案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(...),
      ]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-06
      • 2018-03-19
      • 2020-01-27
      相关资源
      最近更新 更多