【问题标题】:Angular 9 `*ngFor` not working with `Array` of objectAngular 9`*ngFor`不适用于对象的`Array`
【发布时间】:2021-01-06 08:27:34
【问题描述】:
在 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>
结果如下:
我在这里犯了什么错误?
【问题讨论】:
标签:
angular
angular-ngfor
【解决方案1】:
您有一个 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为您创建了一个示例
【解决方案2】:
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 }}
...