javascriptangularangular-materialangular6angular-material-6

Pushing new FormGroup into FormArray marks dynamic FormGroup as invalid


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?


Solution

  • 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);