gpt4 book ai didi

angular - ngFor 内部 ngFor

转载 作者:太空狗 更新时间:2023-10-29 18:06:38 29 4
gpt4 key购买 nike

我有 Angular + Firebase 应用程序。在我的一个组件中,我从 Firebase DB 获取元素并使用 *ngFor 将它们绑定(bind)到模板中:

<div *ngFor="let comment of (comments | async)>
<div>{{ comment.text }}</div>
</div>

但每个评论也有answers列表: firebase db

我如何在我的循环中绑定(bind)答案,例如,像这样:

<div *ngFor="let comment of (comments | async)>
<div>{{ comment.text }}</div>

<div *ngFor="let answer of comment.answers">
{{ answer.text }}
</div
</div>

这个结构不起作用并返回错误:

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

最佳答案

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])
}
}

如果要保留 key ,也可以将其合并到映射调用中的对象中。

export class Component {
toArray(answers: object) {
return Object.keys(answers).map(key => ({
key,
...answers[key]
}))
}
}

关于angular - ngFor 内部 ngFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49921096/

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