How to iterate through "Object carrying an array" using *ngFor in angular?

620 Views Asked by At

I am trying to iterate through an object containing array but getting an error "Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays." Below is my json response:

data={"books": [{"title": "A","edition": 3,"year": 2011 },
{"title": "B","edition": 2,"year": 2009},
{"title": "C","edition": 2,"year": 2008}],
"count":3
}

template code:

<tr *ngFor="let d of data">
<td>d.books.title</td>
</tr>

Can anyone suggest what changes needs to be made to loop through the data?

2

There are 2 best solutions below

2
On

You need to use the array, that is data.books

<tr *ngFor="let d of data.books">
<td>{{d.title}}</td> //edited after looking at comments
</tr>
0
On
In your .ts file is : Declare the data object
  data =
      {"books": 
      [
        {"title": "A","edition": 3,"year": 2011 },
        {"title": "B","edition": 2,"year": 2009},
        {"title": "C","edition": 2,"year": 2008}
      ],
        "count":3
      }

In your .html file:

<table>
    <tr *ngFor="let d of data.books">
     <td>{{d.title}}</td>
    </tr>
</table>

I tried it.. It works for me! enter image description here