Pushing new FormGroup into FormArray marks dynamic FormGroup as invalid

1.1k views Asked by At

I'm not sure if this is a bug, almost 90% certain it's not, but I want to know the logic behind something like this occuring.

I have a component, where let's say I'm initializing a FormGroup on the initialization of the component.

export class FooComponent implements OnInit {
  form!: FormGroup;
  foos!: FormArray;
  constructor(
    private fb: FormBuilder
  ) {}

  ngOnInit(): void {
    this.form = this.fb.group({
      foos: this.fb.array([]),
    });
  }

  createFoo(): FormGroup {
    return this.fb.group({
      name: ['', Validators.required],
      details: ['', Validators.required]
    });
  }

  addFoo(): void {
    this.foos = this.form.get('foos') as FormArray;
    this.foos.push(this.createFoo());
  }
}

Let's say the addFoo() function gets called on a button click (which is how it is in my current application). Why is the newly pushed FormGroup marked as pristine but invalid? Even if there is a solid reason for this, shouldn't one assume that if we're dynamically generating a new FormGroup with validators, it should be considered valid upon creation or push? Is there a way around this? I don't want to have my users click a button to generate a new group of fields to fill out that are already marked invalid when they haven't done anything to those fields themselves. Is this a bug? I don't feel like my implementation is incorrect since I've followed the Angular Material documentation for this. I've tried setting the Validators.required manually after the new foo is pushed into the FormArray but this yields the same result.

Any opinions and/or tips?

2

There are 2 answers

2
Sheik Althaf On BEST ANSWER

For you question here is an answer.

On initial state your this.form is valid

then createFoo() creates a formGroup which is invalid due empty value provided with required validator.

When you try to push invalid formGroup to a valid formGroup Array then this.form get invalid.

If you want valid on push try to add value or remove the required validator

For REF:

FormBuilder creates the Group with formControl like this

new FormControl(value: any, validator: Validators);
0
Jeba On

I had a very similar situation where whenever I added a new formGroup to my formArray its validations would get triggered even though they were untouched & pristine. Turns out if you use a button to dynamically add formGroups it will default the action to a submit event, triggering validations to run if you do not specify the button type.

Adding type="button" resolved the issue

REF: https://stackoverflow.com/questions/58514431/reactive-form-array-avoid-validation-error-when-push-new-elements#:~:text=Reactive%20Form%20Array%20%2D%20Avoid%20Validation%20Error%20when%20push%20new%20elements,-angular%20angular%2Dreactive&text=When%20I%20push%20new%20elements,I%20create%20the%20new%20FormGroup%20.