gpt4 book ai didi

javascript - 动态使用 Angular6 Mat-Table

转载 作者:行者123 更新时间:2023-12-02 22:56:09 25 4
gpt4 key购买 nike

我正在开发一个 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.friendName 之类的内容进行硬编码。我通过如下所示的数组接收应该使用哪些键名。

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

这样做的问题是,它会导致第一个值(“friendName”)在行的每一列上重复。像这样的东西。

enter image description here

虽然预期的工作方式是这样的:

enter image description here

最佳答案

您需要循环 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 来显示正确的列。模板将处理其余部分并将相关数据显示到显示的列。

关于javascript - 动态使用 Angular6 Mat-Table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57969238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com