angular - 面向列的垫表
问题描述
我有一种情况,我从后端收到的数据是面向列的。该数据的外观示例如下:
[
{ columnName: "ID", cells: [1, 2, 3, 4, 5] },
{ columnName: "Name", cells: ["a", "b", "c", "d", "e"] }
]
到目前为止,我已经设法像这样配置我的 mat-table:
<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>
这给了我以下结果:
而实际上我希望看到这样的表格:
|------|------|
| ID | NAME |
|------|------|
| 1 | a |
| 2 | b |
| 3 | c |
| 4 | d |
| 5 | e |
有没有办法调整 matRowDef 以便将单元格属性定义为行?理想情况下,我只想在 mat-table 中更改它,所以我不需要操作我的数据然后再将其转换回来。
解决方案
您可以尝试根据需要修改现有响应:
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 代码:
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);
}
}
推荐阅读
- javascript - 如何在保存另一个文档之前等待循环完成?
- julia - 使用具有多个条件的 findall
- python - Python 输出为列,还添加逗号 (csv)
- node.js - 如何修复“完成请求前进程已退出”
- android - 实体关系 - android
- jelastic - Jelastic - Collabora Online with Next Cloud without ssl(用于测试)
- php - 如何用新行替换 XML 格式的所有 HTML 换行符(
)? - laravel - Laravel Dusk:如何从元素中获取 HTML?
- javascript - localhost 在 Opera 而不是 chrome 中打开。我该如何改变它?
- android - 我的代码中旋转在我的应用程序中捕获的横向图像的正确点是什么?