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]
    }))
  }
}
Share:
11,586
Vladimir Humeniuk
Author by

Vladimir Humeniuk

Updated on June 09, 2022

Comments

  • Vladimir Humeniuk
    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 have answers list: firebase db

    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
      Jaime Cuellar about 6 years
      If you try to get comments.answers what do you get?
  • Tomasz Kula
    Tomasz Kula about 6 years
    Glad I could help :) Please accept my answer if it solved your problem.
  • Vladimir Humeniuk
    Vladimir Humeniuk about 6 years
    yes, i do. By the way, you method does not return me answer.key. How can o solved that?
  • Eric Phillips
    Eric Phillips about 5 years
    Angular 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