首页 > 解决方案 > 使用角度材料表显示数据

问题描述

我有一个不同的数据结构,我需要通过mat-table.

dataSource= [[1,2],[3,4],[5,6]]

这里,dataSource[0]永远是标题。其余的数组项是它的行。

所以上述数据的输出应该如下所示

1 2 Heading of the table

3 4

5 6

上述数据结构可以使用mat-table吗?请帮忙

注意:- 我查看了 mat-table 文档,但我能找到任何对我有帮助的东西

标签: angulartypescriptangular-material

解决方案


您可以实现这一点,您需要提取列名的值并将其与数据分开。

export class TableBasicExample {
  data = [[1,2],[3,4],[5,6]];
  dataSource = this.data.splice(1);
  displayedColumns: string[] = this.data[0].map(value => String(value));
}

在模板中动态绑定这些数据源和列名。

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

    <!--- Note that these columns can be defined in any order.
        The actual rendered columns are set as a property on the row definition" -->

    <!-- Position Column -->
    <ng-container matColumnDef="{{displayedColumns[0]}}">
        <th mat-header-cell *matHeaderCellDef> {{displayedColumns[0]}} </th>
        <td mat-cell *matCellDef="let element"> {{element[0]}} </td>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="{{displayedColumns[1]}}">
        <th mat-header-cell *matHeaderCellDef> {{displayedColumns[1]}} </th>
        <td mat-cell *matCellDef="let element"> {{element[1]}} </td>
    </ng-container>

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

请在此处找到有效的 stackblitz:https ://stackblitz.com/edit/angular-nmnymd


推荐阅读