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([])
    });
  }
2
  • 1
    which form array you want to validate? Commented Dec 13, 2017 at 14:28
  • billing and payment both array Commented Dec 13, 2017 at 14:29

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

3 Comments

you me to use this in constructor or in submit function
place this in you components constructor
But _fb is FormBuilder. shouldn't be billingForm.valueChanges?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.