name.replace 不是具有动态列的 mat table 中的函数

name.replace is not a function in mat table with dynamic columns

我需要使用带动态列的垫子 table,但出现此错误:

> ERROR TypeError: name.replace is not a function
>     at MatColumnDef.set name [as name] (table.js:175)
>     at updateProp (core.js:32189)
>     at checkAndUpdateDirectiveInline (core.js:31867)
>     at checkAndUpdateNodeInline (core.js:44367)
>     at checkAndUpdateNode (core.js:44306)
>     at debugCheckAndUpdateNode (core.js:45328)
>     at debugCheckDirectivesFn (core.js:45271)
>     at Object.eval [as updateDirectives] (TableComponent.html:3)
>     at Object.debugUpdateDirectives [as updateDirectives] (core.js:45259)
>     at checkAndUpdateView (core.js:44271)

在我的 ts 中我声明:

tableConfigurations = {
    dataSource: [],
      columns: [{
        name: 'first'
      },
      {
        name: 'second'
      },
      {
        name: 'third'
      },
      {
        name: 'fourth'
      },
      {
        name: 'fifth'
      }]
  }

在 html 我有:

<table mat-table [dataSource]="tableConfigurations.dataSource" class="mat-elevation-z8">
  <ng-container [matColumnDef]="column" *ngFor="let column of tableConfigurations.columns">

    <ng-container>
      <th mat-header-cell *matHeaderCellDef> {{column.name}} </th>
      <td mat-cell *matCellDef="let element"> {{element[column]}} </td>
    </ng-container>
  </ng-container>

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

</table>

This is the stackblitz 与我当前的代码。正如您在控制台中所看到的,存在相同的错误。我不明白我错过了什么。

问题出在

columns: [{ name: 'first' }, {name: 'second'}, ... ]

您可以采用两种方法:

  1. 列数组将变为字符串数组,如:

    columns: ['first', 'second', ... ]

Angular material table 显示列必须是字符串数组才能解析列。

  1. 添加一个变量,用于将列数组转换为字符串数组,以便正确显示

displayedColumns: any[] = this.tableConfigurations.columns.map(col => col.name);

最后:

你的 html 会像:

<table mat-table [dataSource]="tableConfigurations.dataSource" class="mat-elevation-z8">
  <ng-container [matColumnDef]="column.name" *ngFor="let column of tableConfigurations.columns;">
  <th mat-header-cell *matHeaderCellDef> {{column.name}}</th>
  <td mat-cell *matCellDef="let element"> {{element[column.name]}}</td>
  </ng-container>

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

</table>

Working example