我有一个带有嵌套对象的对象。我尝试使用 Angular 的 ngFor 指令在 html 中显示。但我得到了多次的结果。在我的对象下面
productlists = [
{
productname: 'orange', price:
[{ small: 20 }, { medium: 30 }, { large: 40 }], gst: 12
},
{
productname: 'lemon', price:
[{ small: 40 }, { medium: 80 }, { large: 102 }], gst: 20
},
{
productname: 'apple', price:
[{ small: 40 }, { medium: 80 }, { large: 102 }], gst: 20
}
];
html 代码是
<div style="margin-left: 20rem;">
<div *ngFor="let product of productlists" >
<p style="color: blue;">Product Name {{product.productname}}</p>
<div *ngFor="let productprice of product.price">
Product Price
<p>Small: {{productprice.small}}</p>
<p>Medium: {{productprice.medium}}</p>
<p>Large: {{productprice.large}}</p>
</div>
<p>Product GST {{product.gst}}</p>
</div>
</div>
请帮我正确显示
我们可以使用
keyvalue
管道来分割对象的键和值,以便我们可以单独访问它们。我们使用
titlecase
管道,以便从对象中提取的键以大写首字母显示。我们使用
*ngIf
语法as
来存储来自键值管道的值并使用,ng-container
这样就不会在 HTML 中添加任何额外的元素。完整代码:
Stackblitz 演示