ngFor内部ngFor [英] ngFor inside ngFor
问题描述
我有Angular + Firebase应用程序. 在我的组件之一中,我从Firebase DB中获取了元素,并使用* ngFor将它们绑定到模板中:
I have Angular + Firebase app. In one of my components i get elements from Firebase DB and binding them into template with *ngFor:
<div *ngFor="let comment of (comments | async)>
<div>{{ comment.text }}</div>
</div>
但是每个comment
都有answers
列表:
But every comment
also have answers
list:
我如何在循环中绑定答案,例如:
How can i bind answers inside my loop, for example, something like this:
<div *ngFor="let comment of (comments | async)>
<div>{{ comment.text }}</div>
<div *ngFor="let answer of comment.answers">
{{ answer.text }}
</div
</div>
此结构不起作用并返回错误:
This structure does not work and return error:
找不到类型不同的支持对象"[object Object]" '目的'. NgFor仅支持绑定到数组等Iterable.
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
推荐答案
answers属性是一个对象.在将其显示在*ngFor
循环中之前,必须将其转换为数组.
The answers property is an object. You must convert it into an array, before displaying it in your *ngFor
loop.
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])
}
}
如果要保留键,也可以将其合并到map调用中的对象中.
If you want to keep the key, you can merge it into the object in the map call as well.
export class Component {
toArray(answers: object) {
return Object.keys(answers).map(key => ({
key,
...answers[key]
}))
}
}
这篇关于ngFor内部ngFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!