Lie*_*ero 4 typescript angular-material angular angular-forms angular7
我有一个带有 FormArray 的 FormGroup 和一个显示数组的 mat-table。当我向 FormArray 添加新的 FormGroup 时,mat-table 不会添加新行。
我试图给 trackBy 做广告,但我不知道在哪里(老实说,也不知道为什么)。
组件.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>
Run Code Online (Sandbox Code Playgroud)
和 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()
}));
}
Run Code Online (Sandbox Code Playgroud)
由于该表针对性能进行了优化,因此它不会自动检查数据数组的更改。相反,当在数据数组上添加、删除或移动对象时,您可以通过调用其 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();
}
Run Code Online (Sandbox Code Playgroud)