I have a FormGroup with FormArray and a mat-table that displays the array. When I add new FormGroup to FormArray, the mat-table doesn't add new row.
I was trying to ad trackBy, but I don't know where (and to be honest neither why).
component.html:
<form [formGroup]="formGroup">
<div formArrayName="items">
<button mat-raised-button (click)="addNew()">New Case</button>
<table mat-table [dataSource]="items.controls">
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
<ng-container matColumnDef="itemKey">
<mat-header-cell *matHeaderCellDef> Key </mat-header-cell>
<mat-cell *matCellDef="let item; let i = index" [formGroupName]="i">
<mat-form-field>
<input formControlName="itemKey" matInput />
</mat-form-field>
</mat-cell>
</ng-container>
and the component.ts:
formGroup = new FormGroup({
items: new FormArray()
});
get items() { return this.formGroup.get("items") as FormArray }
addNew() {
this.items.push(new FormGroup({
itemKey: new FormControl(),
itemName: new FormControl()
}));
}
Since the table optimizes for performance, it will not automatically check for changes to the data array. Instead, when objects are added, removed, or moved on the data array, you can trigger an update to the table's rendered rows by calling its renderRows() method.
If a data array is provided, the table must be notified when the array's objects are added, removed, or moved. This can be done by calling the renderRows() function which will render the diff since the last table render. If the data array reference is changed, the table will automatically trigger an update to the rows.
https://material.angular.io/components/table/api#MatTable
Try the following.
@ViewChild(MatTable) _matTable:MatTable<any>;
addNew() {
this.items.push(new FormGroup({
itemKey: new FormControl(),
itemName: new FormControl()
}));
this._matTable.renderRows();
}