我有Angular + Firebase应用。 在我的一个组件中,我从Firebase DB获取元素并使用* ngFor:
将它们绑定到模板中<div *ngFor="let comment of (comments | async)>
<div>{{ comment.text }}</div>
</div>
如何在循环中绑定答案,例如:
<div *ngFor="let comment of (comments | async)>
<div>{{ comment.text }}</div>
<div *ngFor="let answer of comment.answers">
{{ answer.text }}
</div
</div>
此结构不起作用并返回错误:
无法找到不同的支持对象'[object Object]'的类型 '宾语'。 NgFor仅支持绑定到Iterables,例如Arrays。
答案 0 :(得分:6)
answers属性是一个对象。在将其显示在*ngFor
循环中之前,必须将其转换为数组。
<强> component.html 强>
<div *ngFor="let comment of (comments | async)>
<div>{{ comment.text }}</div>
<div *ngFor="let answer of toArray(comment.answers)">
{{ answer.text }}
</div
</div>
<强> component.ts 强>
export class Component {
toArray(answers: object) {
return Object.keys(answers).map(key => answers[key])
}
}
如果你想保留密钥,你也可以将它合并到地图调用中的对象中。
export class Component {
toArray(answers: object) {
return Object.keys(answers).map(key => ({
key,
...answers[key]
}))
}
}
答案 1 :(得分:0)
以下代码对我有用;角7离子4;
<ion-item (click)="navigate(oB.ogretmen_id)" class="OgretmenOzellikler" color="primary" *ngFor="let oB of ogretmenBilgi">
<ion-label>
<h3>{{oB.ogretmen_ad}} {{oB.ogretmen_ad}}</h3>
<ion-label>{{oB.ogretmen_brans}}</ion-label>
<p *ngFor="let key of oB.Dersler">
<ion-icon name="bookmarks"></ion-icon>{{key.ders_ad}}
</p>
</ion-label>
</ion-item>
response of ogretmenBilgi
Dersler: Array(2)
0: {ders_ad: "Vatandaşlık", kategori_ad: "ilk öğretim takviye"}
1: {ders_ad: "Yabancı Dil", kategori_ad: "ilk öğretim takviye"}
length: 2
__proto__: Array(0)
ogretmen_ad: "Ad"
ogretmen_brans: "Brans"