Angular 9`* ngFor`不适用于对象的`Array`

问题描述

在ts文件中,我有这样的数据:

app.component.ts

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

和html模板如下:

app.component.html

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

结果如下:

enter image description here

在这里犯了什么错误

解决方法

您有一个array中的object和一个项目。因此,请尝试以下操作:

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

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

我在Stackblitz上为您创建了一个示例

,

test [object Object]是bcz,您要尝试不重复打印数组。

要打印对象数组而不进行迭代,我们需要使用索引来访问数组值或使用json管道来打印对象或对象数组。

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

或使用数组索引访问

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