Angular Material Header

Angular Material Header

如何在 angular material 中允许重复的 header 值。

我有多个 header,这里的 header 值相同。它给出错误:-

提供了重复的列定义名称

If you read the docs here, you will see the following:

@Input('matColumnDef') name: string

Unique name for this column.

(强调我的)

我假设(因为您没有共享任何代码)您收到此错误的原因是因为您在显示的列数组中多次列出了相同的名称。

解决此问题的一种方法是创建新对象,其中包含 property/column 名称以及供 angular 内部使用的唯一标识符(在我的示例中,我将它们放在一个名为 columnObjects)

组件则变成

export class TableBasicExample {

    // displayedColumns = ['position', 'name', 'name', 'weight', 'symbol'];
   dataSource = ELEMENT_DATA;

   columnObjects = [
       { columnId: 'position', propertyName: 'position' },
       { columnId: 'name1', propertyName: 'name' },
       { columnId: 'name2', propertyName: 'name' },
       { columnId: 'weight', propertyName: 'weight' },
       { columnId: 'symbol', propertyName: 'symbol' }
   ];

   columnIds = this.columnObjects.map(c => c.columnId);
}

并且可以在模板中使用,例如:

<div class="example-container mat-elevation-z8">
  <mat-table #table [dataSource]="dataSource">
    <ng-container [matColumnDef]="col.columnId" *ngFor="let col of columnObjects">
      <mat-header-cell *matHeaderCellDef> {{ col.propertyName }} </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{ element[col.propertyName] }} </mat-cell>
    </ng-container>
    <mat-header-row *matHeaderRowDef="columnIds"></mat-header-row>
    <mat-row *matRowDef="let row; columns: columnIds;"></mat-row>
  </mat-table>
</div>

请注意我是如何只将 columnIds 传递给 angular material 的内部结构的。这是因为它们是独一无二的。

I have created a working example on stackblitz here.

希望这是清楚的。

对于那些因为像 Darren 一样升级到 Angular 9 并带有嵌套 table 的人而结束了这个问题,看起来解决方案是移动嵌套 table 到单独的模板中:

<table mat-table>
...

<!--Move the nested table out of the parent table and into a template, then reference it with a container-->
<ng-container *ngTemplateOutlet="nestedTable; context: { datasource: myRowsChildDatasource }"></ng-container>
...
</table>

<ng-template #nestedTable let-datasource="datasource">
  <table mat-table [dataSource]="datasource">
  </table>
</ng-template>

我有同样的错误,这是我的错误,因为我有 2 个同名的列(在我的例子中是 matColumnDef="email"),所以 matColumnDef 应该是独一无二。

对于像 Darren 这样自更新到 Angular 9 后遇到此问题并且不想将嵌套的 table 移动到单独模板中的人,您可以简单地添加一个 *ngIf到嵌套的 table:

<table mat-table [dataSource]="dataSource" *ngIf="element == expandedElement">

更新: 此 bug 已通过 @angular/material 版本 9.2.0

解决