推动formarray不会更新垫子



我有一个带有formarray的formGroup,并且显示一个显示数组的垫子桌。当我将新的FormGroup添加到FormArray时,Mat-Table不会添加新行。

我试图广告跟踪,但我不知道在哪里(老实说为什么)。

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

由于表优化了性能,因此不会自动检查对数据数组的更改。相反,当在数据数组中添加,删除或移动对象时,您可以通过调用其renderrows()方法来触发表格的渲染行更新。

如果提供了数据阵列,则必须在 添加,删除或移动数组的对象。这可以通过 调用renderrows()函数,该函数将呈现差异 最后一个表渲染。如果更改了数据数组参考,则表 将自动触发对行更新。

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

最新更新