5

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.

Volodymyr Humeniuk
  • 3,411
  • 9
  • 35
  • 70

2 Answers2

16

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]
    }))
  }
}
Tomasz Kula
  • 16,199
  • 2
  • 68
  • 79
0

Below code worked for me; Angular 7 Ionic 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"
abdullah
  • 171
  • 1
  • 2
  • 7