【问题标题】:Angular Material Table get Columns角材料表获取列
【发布时间】:2020-02-22 03:37:16
【问题描述】:

我有一张很大的桌子(很多列)。这就是为什么我要允许用户更改显示的列。我的想法是将所有列放在 MultiSelect 中。为了让它工作,我需要知道所有的 columnIds 才能将它们用作选择选项中的值。为了让它看起来不错,我需要知道列标题单元格的内容,以将它们用作选择选项的显示文本。

这就是表格的样子。

columns = new FormControl(['name','custom1']);
<table mat-table [dataSource]="dataSource">
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> Name </th>
    <td mat-cell *matCellDef="let element"> {{element.name}} </td>
  </ng-container>
  <ng-container matColumnDef="custom1">
    <th mat-header-cell *matHeaderCellDef>My Custom Column</th>
    <td mat-cell *matCellDef="let element"> {{element.custom1}} </td>
  </ng-container>
  <tr mat-header-row *matHeaderRowDef="columns.value"></tr>
  <tr mat-row *matRowDef="let row; columns: columns.value;"></tr>
</table>

所以我需要的选项数据应该是这样的。

const columnOptions = [{columnId: 'name', columnHeader: 'Name'},{columnId: 'custom1', columnHeader: 'My Custom Column'}]

这样,Select 可以看起来像这样。

  <mat-select [formControl]="columns" multiple>
    <mat-option *ngFor="let col of columnOptions" [value]="col.columnId">{{col.columnHeader}}</mat-option>
  </mat-select>

我可以简单地硬编码columnOptions,正如您在上面看到的。但是由于所有必需的数据都存在于 MatTable 中,我想知道是否有任何方法可以从表中获取选项。我一直在向谷歌寻求帮助,有很多关于 MatTable 的内容,但没有解释如何获取有关列的元信息。

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    我建议像您一样在组件中定义columnOptions,然后使用它在模板中动态创建列。这样它只定义在一个地方。

    <ng-container *ngFor="let column of columnOptions">
      <ng-container [matColumnDef]="column.columnId">
        <th mat-header-cell *matHeaderCellDef>{{ column.columnHeader }}</th>
        <td mat-cell *matCellDef="let element"> {{element[column.columnId]}}</td>
      </ng-container>
    </ng-container>
    

    尝试另辟蹊径,从模板中查询列会变得混乱且速度较慢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-21
      • 1970-01-01
      相关资源
      最近更新 更多