验证Angular2中的反应形式

时间:2017-06-01 09:46:17

标签: angular angular2-forms reactive-forms angular-reactive-forms

我有反应形式:

  protected _valueForm = this._formBuilder.group({
    valueCaption: '',
  });

  protected _elementForm = this._formBuilder.group({
    caption: ['', Validators.required],
    required: [false]
  });

然后在ngOnInit()中有一个条件且_elementForm正在发生变化:

      this._elementForm = this._formBuilder.group({
      caption: ['', Validators.required],
      required: false,
      valueForm: this._valueForm,
      values: this._formBuilder.array([])
    },
    {validator: FormElementValidator});

验证

export const FormElementValidator = (control: AbstractControl): ValidationErrors => {
  const values = (control.get('values') as FormArray).value;
  return (!!values.length) ? null : {noValues: 'T_FORM_VALUES_ARE_REQUIRED'};
}

并且效果很好,但如果elementForm为空,则valueCaption无效。为什么会这样,我该如何解决?

1 个答案:

答案 0 :(得分:0)

如果您不想要它,为什么要添加Validators.required 做一些像

这样的事情
protected _elementForm = this._formBuilder.group({
    caption: ['']    
});