首页 > 解决方案 > name.replace 不是具有动态列的 mat 表中的函数

问题描述

我需要使用带有动态列的 mat 表,但出现此错误:

> 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>

这是我拥有的当前代码的堆栈闪电战。正如您在控制台中看到的,存在相同的错误。我不明白我所缺少的。

标签: typescriptangular8mat-table

解决方案


问题在

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

您可以采用两种方法:

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

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

角度材料表显示列必须是字符串数组才能解析列。

  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>

工作示例


推荐阅读