动态表单数组验证Angular 2

时间:2017-12-13 14:24:42

标签: angular angular2-forms angular5

我正在从服务响应创建动态FormGroupFormArray,现在我想验证表单数组,如果任何一个输入有值,否则我不想验证。

this.billingForm = this._fb.group({
   itemRows: this._fb.array([this.initItemRows()])
});

  initItemRows() {
    return this._fb.group({
      Id: '',
      orgName: '',
      billing: this._fb.array([]),
      payment: this._fb.array([])
    });
  }

1 个答案:

答案 0 :(得分:2)

您可以使用以下内容:

// Subscribe to value changes on FormGroup
this._fb.valueChanges.subscribe(c => {
    // Check empty values
    if (this._fb.controls['Id'].value !== '' && this._fb.controls['orgName'].value !== '') {
        // Set validators
        this._fb.controls['billing'].validator = Validators.required; // You can specify any validator method here
        this._fb.controls['payment'].validator = Validators.required;
    } else {
        this._fb.controls['billing'].validator = null;
        this._fb.controls['payment'].validator = null;
    }
});

您可以在此处获取有关自定义验证器的更多信息:Click!