Column oriented mat-table

人盡茶涼 提交于 2019-12-07 23:57:50

问题


I have a situation where the data I receive from my backend is column-oriented. An example of how this data looks like is this:

[
    { columnName: "ID", cells: [1, 2, 3, 4, 5] },
    { columnName: "Name", cells: ["a", "b", "c", "d", "e"] }
]

So far I have managed to configure my mat-table like this:

<table mat-table [dataSource]="data" class="mat-elevation-z8">
    <ng-container [matColumnDef]="column" *ngFor="let column of displayedColumns">
        <th mat-header-cell *matHeaderCellDef> {{column}} </th>
        <td mat-cell *matCellDef="let element">{{element | json}}</td>
    </ng-container>

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

which gives me the following result:

while in reality I'd like to see the table like this:

|------|------|
|  ID  | NAME |
|------|------|
|   1  |   a  |
|   2  |   b  |
|   3  |   c  |
|   4  |   d  |
|   5  |   e  |

Is there some way to adjust the matRowDef so it defines the cells property as rows? Ideally I would just like to change this in the mat-table, so I don't need to manipulate my data and later convert it back.


回答1:


You can try by modifying the existing response as per your need:

HTML Code:

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

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

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

TS Code:

import { Component } from '@angular/core';

import { MatTableDataSource } from '@angular/material';

const ELEMENT_DATA: any[] = [
  { columnName: "ID", cells: [1, 2, 3, 4, 5] },
  { columnName: "Name", cells: ["a", "b", "c", "d", "e"] }
];

/**
 * @title Basic use of `<table mat-table>`
 */
@Component({
  selector: 'table-basic-example',
  styleUrls: ['table-basic-example.css'],
  templateUrl: 'table-basic-example.html',
})
export class TableBasicExample {
  displayedColumns = []
  dataSource = new MatTableDataSource([]);

  constructor() {
    // Take Column names dynamically
    ELEMENT_DATA.forEach(x => {
      this.displayedColumns.push(x.columnName)
    })

    // Format the array as you want to display
    let newlyFormedArray = ELEMENT_DATA.reduce((array, { columnName, cells }) => {
      cells.forEach((cell, index) => {
        array[index] = Object.assign({ [columnName]: cell }, array[index])
      })
      return array;
    }, [])
    this.dataSource = new MatTableDataSource(newlyFormedArray);
  }
}

StackBlitz



来源:https://stackoverflow.com/questions/54036779/column-oriented-mat-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!