您可以尝试根据需要修改现有响应:
HTML 代码:
<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://stackblitz.com/edit/angular-y1buaf