简体   繁体   中英

Angular 9 `*ngFor` not working with `Array` of object

In ts file I have a data like this:

app.component.ts

 this.images = [{
     asset_id: 'asset_id',
     asset_name: 'asset_name'
 }];

and html template is as below:

app.component.html

test {{images}}
<div *ngFor="let img of images; index as i">
  dddd--<span>{{img.asset_id}}</span>
</div>

The result is like the below:

在此处输入图片说明

What is the mistake I am doing here?

You have an array of object with one item. So, try this:

id: {{images[0]["asset_id"]}}
name: {{images[0]["asset_name"]}}

<div *ngFor="let img of images">
    <span>{{ img.asset_id  }}</span>
</div>

I created a sample for you here on Stackblitz

The test [object Object] is bcz you are trying to print array without iteration.

To print array of object without iteration we need to either use index to access array value or use json pipe to print object or array of object.

// output: test [ { "asset_id": "asset_id", "asset_name": "asset_name" } ]
test {{ images | json }}

Or access using array index

{{ images[0].asset_id }}
{{ images[0].asset_name }}
...

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