javascript - 动态使用 Angular6 Mat-Table
问题描述
我正在开发一个 Angular 应用程序,它需要显示从 API 检索到的数据。由于我不确切知道我将检索哪些数据,而且这是我需要用于不同表的模型,我需要让它既动态生成列,又填充每个单元格。
我检索并需要在表中打印的 JSON 类似于:
[
{
"attributes": [],
"brandReference": "f805a08df4c236ddb431e14a38419690",
"computedPOS": "BEXFY_HEADQUARTERS",
"deviceType": 1,
"friendlyName": "BEXFY_TRANSPARENT_LED",
"id": "953e9414d7a51e8-e0-681def0b02b5",
"isMonitored": true,
"location": "entrance",
"posReference": "78fcef0f12993d52b2d2906dc4ce48d8",
"timetable": [],
"timezone": "Europe/Madrid"
},
{
"attributes": [],
"brandReference": "185fd549-4410-462b-a610-fe6b61c91cf6",
"comments": "",
"computedPOS": "BEXFY_HEADQUARTERS",
"deviceType": 1,
"friendlyName": "BEXFY_AUDIO_OFICINA",
"id": "79eaa7f5f6603809-e0-681def0b0290",
"location": "",
"posReference": "78fcef0f12993d52b2d2906dc4ce48d8",
"timetable": [],
"timezone": "Europe/Madrid"
},
{
"attributes": [],
"brandReference": "185fd549-4410-462b-a610-fe6b61c91cf6",
"comments": "",
"computedPOS": "BEXFY_HEADQUARTERS",
"deviceType": 1,
"friendlyName": ".BEXFY_AUDIO_ADRI",
"id": "97bf675e3e237bcd-e0-681def0b029f",
"location": "",
"posReference": "78fcef0f12993d52b2d2906dc4ce48d8",
"timetable": [],
"timezone": "Europe/Madrid"
}
]
请注意,对象属性键可能会更改,因此我无法对 element.friendlyName 之类的内容进行硬编码。我通过如下所示的数组接收我应该使用的键名。
["friendlyName", "computedPOS", "location"]
所以为了让它发挥作用,我做了这样的东西。
<table mat-table [dataSource]="dataSource.data" class="mat-elevation-z8" style="width:90%;margin:0 auto;">
<ng-container *ngFor="let column of modelCols; let colIndex = index" matColumnDef={{nameCols[colIndex]}}>
<th mat-header-cell *matHeaderCellDef> {{nameCols[colIndex]}}</th>
{{log(modelCols)}}
<div *ngFor="let column of modelCols;">
<td mat-cell *matCellDef="let element">
{{log(element[column])}}
{{element[column]}}
</td>
</div>
</ng-container>
<tr mat-header-row *matHeaderRowDef="nameCols"></tr>
<tr mat-row *matRowDef="let row; columns: nameCols;"></tr>
</table>
这样做的问题是,它会导致在行的每一列上重复第一个值(“friendlyName”)。像这样的东西。
虽然预期的工作方式是这样的:
解决方案
您需要循环nameCols
显示您的动态列。无论您的 API 要求您显示什么列,您都需要迭代以显示您的列。由于您element[column]
用于在行中显示项目。它只会显示需要的项目。
<ng-container *ngFor="let column of nameCols; let colIndex = index" [matColumnDef]="column">
<th mat-header-cell *matHeaderCellDef>{{column}}</th>
<td mat-cell *matCellDef="let element">{{element[column]}}</td>
</ng-container>
这是StackBlitz上的一个工作示例,其中包含您的数据。这样即使一组不同的列来自 API 来显示,您需要做的只是更新nameCols
以显示正确的列。模板将处理其余部分并将相关数据显示到显示的列中。
推荐阅读
- java - 线程如何影响打印功能以及何时调用(Java)
- java - 如何使用 Get 请求特别处理 REST API 中的保留字符,例如值 M&S
- typescript - TypeScript 可以推断对象的属性吗?
- vue.js - 为什么我的 Vue/Nuxt Select 字段状态默认有效?
- android - 这样的布局将如何实现?
- fortran - 在 Fortran 中创建的 HDF5 文件直到模拟结束才写入
- javascript - 悬停时更改 SVG 圆形平铺世界地图上区域的颜色
- javascript - 简化旧的 RegExp
- ios - 创建自定义 Xcode 项目模板
- c++ - c++向量如何
> 管理内存