首页 > 解决方案 > 使用 Angular 在表格中添加新行

问题描述

所以我试图在一个从 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);
}

标签: angular-material

解决方案


对变量的引用dataSource不会更新。角度变化检测器并不总是可以(有时可以)识别这种变化。创建新引用(在这种情况下为新数组)应该可以解决这个问题:

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

推荐阅读