Jason Jason - 4 months ago 26
AngularJS Question

Displaying data in html file from json using Angular2

I am trying to pass data from a json feed to the html file, the below is not working.

app.component.html

<ul *ngFor="let unit of units">
<li>
{{unit.details.count}} // getting data OK result -> 5642
</li>
<li>
{{unit.cars.vehicle_id}} // not getting data
</li>
</ul>


units_feed.json

[{"details":{"count":"5642"},"cars":[{"vehicle_id":"2056437754"},{"vehicle_id":"2056437753"},{"vehicle_id":"2056356347"},{"vehicle_id":"2056437752"},{"vehicle_id":"2056395634"}]}]

Answer

You cant access it as unit.cars is an array of object. If You wanted to access one of those objects i.e. ones with the vehicle_id you could use {{unit.cars[0].vehicle_id}}. Notice the [0] that telling it to access the first item in the array and the you can view its property vehicle_id.

Would guess you would have to do something like this

<ul *ngFor="let unit of units">
  <li>
    {{unit.details.count}} 
  </li>
  <li *ngFor="let car of unit.cars">{{car.vehicle_id}}</li>
</ul>