ngFor inside ngFor
11,586
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])
}
}
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]
}))
}
}
Author by
Vladimir Humeniuk
Updated on June 09, 2022Comments
-
Vladimir Humeniuk about 2 years
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>
But every
comment
also haveanswers
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:
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
-
Jaime Cuellar about 6 yearsIf you try to get
comments.answers
what do you get?
-
-
Tomasz Kula about 6 yearsGlad I could help :) Please accept my answer if it solved your problem.
-
Vladimir Humeniuk about 6 yearsyes, i do. By the way, you method does not return me
answer.key
. How can o solved that? -
Eric Phillips about 5 yearsAngular now has support for iterating an object's keys directly with the keyvalue pipe
*ngFor="let item of myObj | keyvalue"
-- see docs angular.io/api/common/KeyValuePipe