How to populate FormArray inside Mat Table?

210 Views Asked by At

I am trying to create a material table with FormArray. But the problem is it's not setting the formContolName. Below is the code I have written:

TS

form = this.fb.group({
  production: this.fb.array([this.initProductionForm()])
});

initProductionForm(): FormControl {
  return this.fb.control({
    proddate: [''], shift: [''], machine: [''], run: [''], operator: [''], helper: ['']
  });
}

createTable() {
  this.dataSource = new MatTableDataSource<any>((this.complaintForm.get('production') as FormArray).controls);
  this.dataSource.paginator = this.paginator;
}

ngOnInit() {
  this.createTable();
}

HTML

<form [formGroup]="form">
  <div class="mat-elevation-z8">
    <table mat-table [dataSource]="dataSource">
      <ng-container matColumnDef="{{column}}" *ngFor="let column of columnsToDisplay; index as i">
        <th mat-header-cell *matHeaderCellDef>
          {{ 
            column == 'proddate' ? 'Date' : column == 'machine' ? 'Mach#' :
            column == 'run' ? 'Run#' : column
          }}
        </th>
        <td mat-cell *matCellDef="let element" [formGroup]="element">
          <input type="date" class="form-control tdfields" *ngIf="column=='proddate'" formControlName="proddate">
          <input class="form-control tdfields" *ngIf="column=='shift'" formControlName="shift">
          <input class="form-control tdfields" *ngIf="column=='machine'" formControlName="machine">
          <input class="form-control tdfields" *ngIf="column=='run'" formControlName="run">
          <input class="form-control tdfields" *ngIf="column=='operator'" formControlName="operator">
          <input class="form-control tdfields" *ngIf="column=='helper'" formControlName="helper">
        </td>
      </ng-container>
      <tr mat-header-row *matHeaderRowDef="columnsToDisplay; sticky: true"></tr>
      <tr mat-row *matRowDef="let element; columns: columnsToDisplay;"></tr>
    </table>
    <mat-paginator [pageSizeOptions]="[5, 1, 10, 20, 50, 100]" showFirstLastButtons></mat-paginator>
  </div>
</form>

I have followed this Stackblitz example. The error I am getting is this:

error

Can anyone tell me how to solve it ? I have tried formGroupName instead of formGroup but still no change. Please help me out.

1

There are 1 best solutions below

1
On

wrap input inside <mat-form-field> to be able to use formControl or formControlName.