【问题标题】:Displaying data using angular Material Table使用角度材料表显示数据
【发布时间】:2020-07-24 06:43:33
【问题描述】:

我有一个不同的数据结构,我需要通过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 文档,但我能找到任何对我有帮助的东西

【问题讨论】:

    标签: angular typescript angular-material


    【解决方案1】:

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

    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

    【讨论】:

      【解决方案2】:

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

      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 创建表columns 如下:

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

      这是工作示例:demo

      【讨论】:

        猜你喜欢
        • 2021-01-11
        • 1970-01-01
        • 1970-01-01
        • 2021-05-08
        • 2019-11-26
        • 2021-04-27
        • 1970-01-01
        相关资源
        最近更新 更多