下面是我的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
}
]
}
我想显示这些属性即。表中的value,count和tagName(使用tagId获取)。对于我使用ngFor的前两个属性。但是,我想打印tagName,我正在使用tagId并将其存储在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>
但我在列tag-name下得到[object object]。有人可以帮我解决这个问题吗?
我尝试使用上面的ng-container,但结果在UI上看起来像这样:
哪个错了。我只需要前3行,标记名称分别为“Subtag 3”,“Zeit1”,“Tag 1”,分别为1,2,3行。
提前致谢。
答案 0 :(得分:3)
你不能在一个元素上加倍*ngFor
。您可以使用辅助元素<ng-container>
,如
<tr *ngFor="let frequency of frequencies; let i=index">
<ng-container *ngFor="let name of tagNames">
<td>{{ frequency.value }}</td>
<td>{{ name }}</td>
<td>{{ frequency.count }}</td>
</ng-container>
</tr>
答案 1 :(得分:3)
您可以使用索引变量,迭代* ngFor中的频率数组并将其索引用于tagNames
<tr *ngFor="let frequency of frequencies; let i=index">
<td>{{ frequency.value }}</td>
<td>{{ tagNames[i] }}</td>
<td>{{ frequency.count }}</td>
</tr>
确保已初始化tagNames:
tagNames:string [] = [];