0

Imagine the following FormGroup in Angular:

this.form = new FormGroup({
  name: new FormControl(''),
  age: new FormControl(),
  hobbies: new FormArray([])
}, {
  validators: [this.validateForm.bind(this)]
});

I am later adding hobbies in FormArray using:

this.form.controls.hobbies.controls.push(new FormControl(/* hobby */));

When I change values in name and age controls, the validateForm function is triggering fine. But when I click on either of the hobbies, aforementioned validation method isn't getting called.

1
  • What does this.validateForm look like? Commented Jan 1, 2021 at 20:26

2 Answers 2

2

I figured this out (it was a stupid mistake at my end).

Instead of adding new FormControl using:

this.form.controls.hobbies.controls.push(new FormControl(/* hobby */))

I should've added it on the hobbies itself, e.g.

const hobbies = this.form.controls.hobbies as FormArray;
hobbies.push(new FormControl(/* hobby */));

Above code adds to the same controls array, but Angular does a bunch of internal stuff to register the control with itself. So in previous solution, a new control would be added to the hobbies, but Angular won't know about it. But in the new, Angular will handle the stuff for us internally.

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

Comments

0

I think because you need to pupulate the formArray with a formGroup for example:

  form = new FormGroup({
    name: new FormControl(''),
    skills: new FormArray([
      new FormGroup({
        name: new FormControl(''),
        level: new FormControl('')
      })
    ])
  });

you can find some good explanation here:

https://netbasal.com/angular-reactive-forms-the-ultimate-guide-to-formarray-3adbe6b0b61a

1 Comment

Thanks for commenting. Having formGroup inside a formArray would defeat the intended purpose I chose formArray for in the first place, i.e. add new FormControl dynamically and loop to display new controls.

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.