Muthamizhchelvan. V
Muthamizhchelvan. V

Reputation: 1261

Dynamic form array validation Angular 2

I am creating dynamic FormGroup and FormArray from the service response, Now I wanted to validate the form array if any one of the input has value else I don't want to validate.

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

Upvotes: 2

Views: 1152

Answers (1)

Crappy
Crappy

Reputation: 451

You could use something like this:

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

You can get more information on custom validators here: Click!

Upvotes: 2

Related Questions