Angular 9 `*ngFor` 不适用于对象的 `Array`
Angular 9 `*ngFor` not working with `Array` of object
在 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>
结果如下:
我这里犯了什么错误?
您有一件商品 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]
是因为您正在尝试不迭代地打印数组。
要在不迭代的情况下打印对象数组,我们需要使用索引来访问数组值或使用 json
管道打印对象或对象数组。
// output: test [ { "asset_id": "asset_id", "asset_name": "asset_name" } ]
test {{ images | json }}
或使用数组索引访问
{{ images[0].asset_id }}
{{ images[0].asset_name }}
...
在 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>
结果如下:
我这里犯了什么错误?
您有一件商品 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]
是因为您正在尝试不迭代地打印数组。
要在不迭代的情况下打印对象数组,我们需要使用索引来访问数组值或使用 json
管道打印对象或对象数组。
// output: test [ { "asset_id": "asset_id", "asset_name": "asset_name" } ]
test {{ images | json }}
或使用数组索引访问
{{ images[0].asset_id }}
{{ images[0].asset_name }}
...