使用 Angular 在 table 中添加新行

Adding a new line in the table with Angular

所以我试图在 table 中添加一个新行,该行是从 API 填充的,但看起来我错过了一些东西。 这是我的代码:

HTML:

<button mat-flat-button color="primary" class="btn-add" 
    (click)="addRow()" 
    [disabled]="isLoading">ADD</button>

<table mat-table [dataSource]="dataSource" class="mat-elevation-z2" *ngIf="show">
  <ng-container *ngFor="let column of displayedColumns" [matColumnDef]="column">
    <th mat-header-cell *matHeaderCellDef>{{column}}</th>
    <td mat-cell *matCellDef="let element; index as i;">
      <span *ngIf="element.editing; then editBlock else displayBlock"></span>
      <ng-template #displayBlock>{{element[column]}}</ng-template>
      <ng-template #editBlock>
        <mat-form-field appearance="fill">
          <input matInput [(ngModel)]="element[column]">
        </mat-form-field>
      </ng-template>
    </td>
  </ng-container>
  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

TS 文件:

displayedColumns: string[] = [];
dataSource: any;

addRow() {
  console.log("Adding new row");
  let newRow = {
    editing: true
  };
  this.displayedColumns.forEach(x => newRow[x] = "");
  this.dataSource.push(newRow);
}

对变量 dataSource 的引用未更新。 Angular 变化检测器并不总是能够(虽然有时能够)识别此类变化。创建新引用(在本例中为新数组)应该可以解决此问题:

addRow() {
  let newRow = { editing: true };
  this.displayedColumns.forEach(x => newRow[x]="");
  this.dataSource = [...dataSource, newRow];
}

您错过了 table.renderRows() 通话

Documentation:

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.

HTML

<table #elementTable mat-table class="mat-elevation-z2"
    *ngIf="show"
    [dataSource]="dataSource">

TS

@ViewChild('elementTable') matTable: MatTable<any>;

并且在addRow()函数中

addRow() {
  console.log("Adding new row");
  const newRow: any = {
    column: '',
    editing: true
  };
  this.dataSource.push(newRow);
  this.table.renderRows();
}