推送到 FormArray 不会更新 may-table

Push to FormArray doesnt update mat-table

我有一个带有 FormArray 的 FormGroup 和一个显示数组的 mat-table。 当我将新的 FormGroup 添加到 FormArray 时,mat-table 不会添加新行。

我想在 trackBy 上做广告,但我不知道在哪里(老实说,也不知道为什么)。

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>

和 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()
  }));
}

由于table 优化了性能,它不会自动检查数据数组的变化。相反,当在数据数组上添加、删除或移动对象时,您可以通过调用其 renderRows() 方法触发对 table 呈现行的更新。

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


试试下面的方法。

@ViewChild(MatTable) _matTable:MatTable<any>;

 addNew() {
    this.items.push(new FormGroup({
      itemKey: new FormControl(),
      itemName: new FormControl()
    }));
    this._matTable.renderRows();
  }