我们可以使用
keyvalue
管道分割对象的键和值,以便我们可以单独访问它们。
我们使用
titlecase
管道,以便从对象中提取的密钥以首字母大写的方式显示。
我们使用
*ngIf
s
as
存储键值管道中的值并使用的语法
ng-container
从而不会向HTML添加额外的元素。
<div style="margin-left: 20px;">
<div *ngFor="let product of productlists" >
<p style="color: blue;">Product Name {{product.productname}}</p>
Product Price
<div *ngFor="let productprice of product.price">
<ng-container *ngIf="productprice | keyvalue as productPriceObj">
<p>{{productPriceObj[0].key | titlecase}}: {{productPriceObj[0].value}}</p>
</ng-container>
</div>
<p>Product GST {{product.gst}}</p>
</div>
</div>
完整代码:
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-root',
imports: [CommonModule],
template: `
<div style="margin-left: 20px;">
<div *ngFor="let product of productlists" >
<p style="color: blue;">Product Name {{product.productname}}</p>
Product Price
<div *ngFor="let productprice of product.price">
<ng-container *ngIf="productprice | keyvalue as productPriceObj">
<p>{{productPriceObj[0].key | titlecase}}: {{productPriceObj[0].value}}</p>
</ng-container>
</div>
<p>Product GST {{product.gst}}</p>
</div>
</div>
`,
})
export class App {
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,
},
];
}
bootstrapApplication(App);