简体   繁体   中英

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

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?

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>
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! 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM