角材料头

时间:2018-08-21 12:14:18

标签: angular angular-material2

如何在角形材质中允许重复的标题值。

我有多个标头,此处标头值相同。它给出了错误:-

提供了重复的列定义名称

4 个答案:

答案 0 :(得分:3)

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

  

@Input('matColumnDef')名称:字符串

     此列的

唯一名称。

(重点是我的)

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

一种解决方法是创建一个新对象,该对象包含属性/列名以及用于内部使用的angular的uniqueIdentifier(在我的示例中,我将它们放在名为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传递给角形材料的内部。这是因为它们是唯一的。

I have created a working example on stackblitz here.

希望这很清楚。

答案 1 :(得分:2)

对于自从更新Angular 9(例如Darren)以来不希望将嵌套表移动到单独模板中的那些人,您只需将* ngIf添加到嵌套表中即可:

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

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

答案 2 :(得分:0)

对于那些由于使用嵌套表(如Darren)升级到Angular 9而最终解决了这个问题的人,看来解决方案是将嵌套表移到单独的模板中:

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

答案 3 :(得分:0)

我有相同的错误,这是我的错误,因为我有两个名称相同的列(在我的情况下为var name = "Bob"; if (name == "Bob") { let fullName = "Bob Smith"; console.log(fullName); } ),所以 matColumnDef 应该是唯一的。

相关问题