首页 > 解决方案 > 将动态列添加到 mat-table 并单击内联更改列标题

问题描述

我尝试在单击按钮时构建材料表,我可以添加/删除列和表行。我尝试添加

displayedColumns: string[] = ['name', 'weight', 'symbol', 'position'];
  columnsToDisplay: string[] = this.displayedColumns.slice();
  data: PeriodicElement[] = ELEMENT_DATA;

  addColumn() {
    const randomColumn = Math.floor(Math.random() * this.displayedColumns.length);
    this.columnsToDisplay.push(this.displayedColumns[randomColumn]);
  }
 removeColumn() {
    if (this.columnsToDisplay.length) {
    this.columnsToDisplay.pop();
  }

这是堆栈闪电战

我得到了添加/删除列,但我无法进行内联编辑。有什么办法可以让它工作吗?

谢谢

标签: angularangular-material

解决方案


当您单击该单元格时,一种可能的解决方案是显示输入而不是单元格的标签。然后通过使用 ngModel 指令 ( https://angular.io/api/forms/NgModel ),您将输入的值直接绑定到 ELEMENT_DATA 数组,使您可以看到直接反映在表上的更改。

在你的 component.html

    <table mat-table [dataSource]="data" class="mat-elevation-z8">
        <ng-container [matColumnDef]="column" 
         *ngFor="let column of displayedColumns; let columnIndex = index;">
            <th mat-header-cell *matHeaderCellDef> {{column}} </th>
            <td mat-cell *matCellDef="let element">
                <span (click)="onEdit(element.position, columnIndex)" 
            *ngIf="!cellEditting(element.position, columnIndex)">
            {{element[column]}}
          </span>
          <input type="text" [(ngModel)]="data[element.position -1 ][column]" 
           *ngIf="cellEditting(element.position, columnIndex)">
        <button type="button" *ngIf="cellEditting(element.position, columnIndex)"
          (click)="onClose(element.position, column)" >Close</button>
        </td>
    </ng-container>

        <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
        <tr mat-row *matRowDef="let row; columns: columnsToDisplay;"></tr>
    </table>

在你的 component.ts

 //will keep track of the cell currently being editted
 edittedCell = { row: -1, column: -1 };
 onEdit(row: number, column: number) {
    this.edittedCell = { row, column };
  }

  cellEditting(row: number, column: number): boolean {
    return column === this.edittedCell.column && row === this.edittedCell.row;
  }

  onClose(row: number, column: string, input) {
      this.edittedCell = {row: -1, column: -1}
  }

推荐阅读