0
votes

I'm trying to dynamically control the number of FormGroups with a FormArray such that I set the FormArray length.

myForm = this.fb.group({
  formGroupsToAdd: ['5'],
  formList: this.fb.array(this.getFormControls(5))
});

getFormControls(numberOfFormGroups: number) {
  const myArray = new Array(numberOfFormGroups);
  myArray.fill(this.fb.group({
    length: [''],
    width: [''],
    height: ['']
  }));
  return myArray;
}

I also have a way of getting this formList: FormArray with

get unitList() {
  return this.myForm.get('formList') as FormArray;
}

However, when I go to add a value to a single control in this FormArray, it updates all FormGroups in the FormArray.

<div formArrayName="formList">
  <div *ngFor="let unitForm of formList.controls; let i = index">
    <div [formGroup]="formList.controls[i]">
      <pre>{{formList.controls[i].value | json}}</pre>
      <pre>i = {{i}}</pre>
      <mat-form-field>
        <input matInput formControlName="length" />
      </mat-form-field>
      <mat-form-field>
        <input matInput formControlName="width" />
      </mat-form-field>
      <mat-form-field>
        <input matInput formControlName="height" />
      </mat-form-field>
    </div>
  </div>
</div>

So my formList.value looks like this...

[
  {
    "length": "",
    "width": "asdf",
    "height": ""
  },
  {
    "length": "",
    "width": "asdf",
    "height": ""
  },
  {
    "length": "",
    "width": "asdf",
    "height": ""
  },
  {
    "length": "",
    "width": "asdf",
    "height": ""
  },
  {
    "length": "",
    "width": "asdf",
    "height": ""
  }
]

Where instead I need a single FormGroup to contain of course it's own unique FormControl values.

What am I doing wrong? Why doesn't the [formGroup]="formList.controls[i]" satisfy my need here by providing a unique identifier for each formGroup?