gpt4 book ai didi

Angular mat-table 显示每行中键值 json 的动态数据

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

我有以下 json 并希望以 Angular 在 Material 表中渲染

var res = '[
{
"DynamicName": "xyz",
"DynamicLevel": "xyz",
"DynamicLevel": "xyz",
"DynamicLevel": "xyz",
"dynamic": "xyz"
},
{
"DynamicName": "xyz",
"DynamicLevel": "xyz",
"DynamicLevel": "xyz",
"DynamicLevel": "xyz",
"dynamic": "xyz"
},
{
"DynamicName": "xyz",
"DynamicLevel": "xyz",
"DynamicLevel": "xyz",
"DynamicLevel": "xyz",
"dynamic": "xyz"
}]';

在第二个响应中,这个 json 将如下所示

var res = '[
{
"DynamicCity": "xyz",
"DynamicCountry": "xyz",
"DynamicState": "xyz",
"DynamicRegion": "xyz",
"dynamic": "xyz"
},
{
"DynamicCity": "xyz",
"DynamicCountry": "xyz",
"DynamicState": "xyz",
"DynamicRegion": "xyz",
"dynamic": "xyz"
},
{
"DynamicCity": "xyz",
"DynamicCountry": "xyz",
"DynamicState": "xyz",
"DynamicRegion": "xyz",
"dynamic": "xyz"
}]';

此数据需要在 Material 表中呈现我已经尝试过这样

// properties of the class
displayedColumns: string[];//columns should be create dynamically
dataSource = res;

<table mat-table [dataSource]="dataSource | keyvalue" class="mat-elevation-z8">
<ng-container matColumnDef="key">
<th mat-header-cell *matHeaderCellDef> {{element.key}}</th>
<td mat-cell *matCellDef="let element"> {{element.value}} </td>
</ng-container>

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

I need output like below

enter image description here

这里,动态列意味着在每个 api 调用中,我们都会获得该列名称的不同数据,因此每次 api 调用都会更改它,因此我无法将其绑定(bind)到 Material 表。请帮我解决将json数据绑定(bind)到 Material 表的问题。引用网址:-

  1. Angular mat-table display dynamic key value pair in each row
  2. https://www.interfacecreator.com/2018/10/angular-material-table-dynamic.html

最佳答案

我为你创建了一个 Stackblitz。这应该适用于任何具有简单值的对象的列表(将从第一个对象获取键,因此当前列表的所有对象都必须相同(如果不创建单独的表,就无法解决这个问题)): https://stackblitz.com/edit/angular-pqgny8?file=src/app/table-basic-example.html

HTML:

<table *ngIf="dataSource && displayedColumns" mat-table [dataSource]="dataSource" class="mat-elevation-z8">

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

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

TS:

getData() {
this.dataSource = ELEMENT_DATA; // ELEMENT_DATA is the data from your backend
this.displayedColumns = Object.keys(this.dataSource[0]).map(k => k)

}

关于Angular mat-table 显示每行中键值 json 的动态数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68082556/

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