Angular 使用角材质表显示数据

Angular 使用角材质表显示数据,angular,typescript,angular-material,Angular,Typescript,Angular Material,我有一个不同的数据结构,我需要通过mat table来显示它 dataSource= [[1,2],[3,4],[5,6]] 在这里,dataSource[0]始终是标题。其余的数组项是它的行 因此,上述数据的输出应如下所示 12表格标题 34 5.6 上述数据结构是否可以使用mat table?请帮忙 注意:-我已经查阅了mat表文档,但是我可以找到任何有助于我的东西如果要实现这一点,需要提取列名的值并将其与数据分离 export class TableBasicExample { da

我有一个不同的数据结构,我需要通过
mat table
来显示它

dataSource= [[1,2],[3,4],[5,6]]
在这里,
dataSource[0]
始终是标题。其余的数组项是它的行

因此,上述数据的输出应如下所示

12
表格标题

34

5.6

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


注意:-我已经查阅了mat表文档,但是我可以找到任何有助于我的东西

如果要实现这一点,需要提取列名的值并将其与数据分离

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>

{{displayedColumns[0]}
{{元素[0]}
{{displayedColumns[1]}
{{元素[1]}

请在此处找到正在工作的stackblitz:

以根据您拥有的数据创建完全动态的表。您可以执行以下操作:

component.ts
文件中:

public data: any[] = [['age', 'height'], [3, 4], [5, 6]]
  public dataSource: any[] = [];
  displayedColumns: string[] = [];
  isDataReady: boolean = false;

  constructor() {
    this.displayedColumns = this.data[0];
    let tempArr = this.data.slice(1, this.data.length);
    tempArr.forEach((el: any[]) => {
      let obj: any = {};
      el.forEach((key, i) => {
        obj[this.displayedColumns[i]] = key;
      });
      this.dataSource.push(obj);
    });
  }
然后在
component.html
中创建表
,如下所示:

<ng-container *ngFor="let col of displayedColumns" [matColumnDef]="col">
    <th mat-header-cell *matHeaderCellDef> {{col}} </th>
    <td mat-cell *matCellDef="let element"> {{element[col]}} </td>
  </ng-container>

{{col}}
{{element[col]}
以下是工作示例: