gpt4 book ai didi

angular - 以 Angular 表的形式迭代

转载 作者:行者123 更新时间:2023-12-03 15:28:23 27 4
gpt4 key购买 nike

我正在尝试以表格的形式迭代列表。以下列表应使用 *ngFor 以表格形式呈现:

我/p :

let list = [
{
"key1": {
"subkey1": [
1,
2,
3,
1
],
"subkey2": [
3,
2,
3,
4
]
}
},
{
"key2": {
"subkey1": [
1
],
"subkey2": [
0
]
}
}
]

表格格式(这是表格的呈现方式):
Categories | subkey1 | subkey2

key1 | 1,2,3,1 | 3,2,3,4

key2 | 1 | 0

我试过了,但它错了:

我试图在 component.html 中迭代的代码:
 <table border="1">
<thead>
<tr>
<th>Categories</th>
<th *ngFor="let each of categoriesHeading"> {{each}} </th> // Array of subkeys
</tr>
</thead>
<tbody *ngFor="let each of categoriesList">
<tr>
<td *ngFor="let key of objectKeys(each)">// iterating keys
{{key}}
</td>
<td> </td> // I don't know how to itereate the values of each subkey of key [1,2,3]
</tr>
</tbody>
</table>

我无法共享 StackBlitz。所以我分享这个截图:
enter image description here

如果有什么遗漏,请告诉我。

最佳答案

您可以根据需要排列数据,然后在模板中显示。

像这样尝试:

Working Demo

Controller :

  categoriesHeading = [];
displayData = [];

constructor() {
this.categoriesHeading = Object.keys(this.list[0].key1);

this.list.forEach(item => {
let obj = {};
obj["key"] = Object.keys(item)[0];
Object.keys(item[Object.keys(item)[0]]).forEach((subkey, i) => {
obj[subkey] = item[Object.keys(item)[0]][subkey].join();
});
this.displayData.push(obj);
});
}

模板:
<table border="1">
<thead>
<tr>
<th>Categories</th>
<th *ngFor="let each of categoriesHeading"> {{each}} </th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of displayData">
<td *ngFor="let each of item | keyvalue"> {{each.value}} </td>
</tr>
</tbody>
</table>

NOTE: For Angular 4, if you don't want to use (keyvalue pipe), then do the following.



TS:
objectKeys = Object.keys;

模板:
<table border="1">
<thead>
<tr>
<th>Categories</th>
<th *ngFor="let each of categoriesHeading"> {{each}} </th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of displayData">
<td *ngFor="let key of objectKeys(item)"> {{item[key]}} </td>
</tr>
</tbody>
</table>

关于angular - 以 Angular 表的形式迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58518929/

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