Array of formGroup within mat-table for each row

It’s difficult help if we can’t get access to the code.

In this stackblitz I put a simple example. See that we create a form Array like

myformArray = new FormArray([
    new FormGroup({
      name: new FormControl("uno"),
      surname: new FormControl("one")
    }),
    new FormGroup({
      name: new FormControl("dos"),
      surname: new FormControl("two")
    }),
    new FormGroup({
      name: new FormControl("tres"),
      surname: new FormControl("three")

    })])

The dataSource of the table is the formArray controls.

  dataSource = this.myformArray.controls;

In this way, “element” is a FormGroup, so a cell can be like

  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> Name </th>
    <td mat-cell *matCellDef="let element">
       <input [formControl]="element.get('name')">
       </td>
  </ng-container>

See that we use [formControl]. That’s. A mat-table iterate over myformArray.controls, that is only an array of FormGroups. The FormGroup is this “element”, so element.get(‘…’) is a FormControl. It’s the reason we can use [formControl]=element.get(‘…’)

it’s like we write not mat-table

<div *ngFor="let element of myformArray.controls">
  <input [formControl]="element.get('name')">
  <input [formControl]="element.get('surname')">
</div>

Leave a Comment