gpt4 book ai didi

angular - 使用 2 个不同的 *ngFor 填充表

转载 作者:太空狗 更新时间:2023-10-29 17:48:24 25 4
gpt4 key购买 nike

下面是我的 JSON 对象数组:

{
"tagFrequency": [
{
"value": "aenean",
"count": 1,
"tagId": 251
},
{
"value": "At",
"count": 1,
"tagId": 249
},
{
"value": "faucibus",
"count": 1,
"tagId": 251
},
{
"value": "ipsum",
"count": 1,
"tagId": 251
},
{
"value": "lobortis",
"count": 1,
"tagId": 194
},
{
"value": "molestie",
"count": 1,
"tagId": 251
},
{
"value": "unde tempor, interdum ut orci metus vel morbi lorem. Et arcu sed wisi urna sit egestas fringilla, at erat. Dolor nunc.",
"count": 1,
"tagId": 199
},
{
"value": "Vestibulum",
"count": 1,
"tagId": 251
}
]
}

我想显示这些属性即。表中的值、计数和标签名称(使用 tagId 获取)。对于前两个属性,我使用 ngFor。但是,我还想打印使用 tagId 获取的 tagName 并将其存储在 tagNames 数组中。以下是我的组件代码:

frequencies: any;
tagNames: string[] = [];

ngOnInit() {
if (this.route.snapshot.url[0].path === 'tag-frequency') {
let topicId = +this.route.snapshot.params['id'];

this.tagService.getTagFrequency(topicId)
.then(
(response: any) => {
this.frequencies = response.json().tagFrequency
for(let tagFrequency of this.frequencies) {
this.getTagName(tagFrequency.tagId)
}
}
)
.catch(
(error: any) => console.error(error)
)
}
}

getTagName(tagId: number): string {
return this.tagService.getTag(tagId)
.then(
(response: any) => {
this.tagNames.push(response.name)
}
)
.catch(
(error: any) => {
console.error(error)
}
)
}

这就是我尝试在 UI 上打印它们的方式:

<table>
<thead>
<tr>
<th>{{ 'word' }}</th>
<th>{{ 'tag-name' }}</th>
<th>{{ 'frequency' }}</th>
<th></th>
</tr>
</thead>
<tbody>
<ng-container *ngFor="let name of tagNames">
<tr *ngFor="let frequency of frequencies; let i=index">
<td>{{ frequency.value }}</td>
<td>{{ name }}</td>
<td>{{ frequency.count }}</td>
</tr>
</ng-container>
</tbody>
</table>

但是我在标签名列下得到了 [object object]。有人可以帮我解决这个问题吗?

我尝试像上面那样使用 ng-container,但在 UI 上结果看起来像这样: tag-name-issue

这是错误的。对于第 1、2、3 行,我只需要前 3 行的标签名称分别为“Subtag 3”、“Zeit1”、“Tag 1”。

提前致谢。

最佳答案

您可以使用索引变量,遍历 *ngFor 中的频率数组并将其索引用于标签名

<tr *ngFor="let frequency of frequencies; let i=index">
<td>{{ frequency.value }}</td>
<td>{{ tagNames[i] }}</td>
<td>{{ frequency.count }}</td>
</tr>

确保你已经初始化了标签名:

标签名称:字符串[] = [];

关于angular - 使用 2 个不同的 *ngFor 填充表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42737858/

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