3 回答

TA贡献1795条经验 获得超7个赞
您可以使用如下所示的三元运算符简单地执行此操作。
<ng-container *ngFor="let cartitem of cart" >
<span class="count">
{{cartitem.p_id==item.p_id ? cartitem.qty : 0 }}
</span>
</ng-container>

TA贡献1806条经验 获得超8个赞
可以在 for 循环中使用 *ngIf else 条件 -
<ion-item class="added" *ngFor="let item of fetchProducts();let key=index;">
<ng-container *ngFor="let cartitem of cart">
<span class="count" *ngIf="cartitem.p_id==item.p_id; then content else other_content">
</span>
<ng-template #content>{{cartitem.qty}}</ng-template>
<ng-template #other_content>0</ng-template>
</ng-container>
</ion-item>

TA贡献1155条经验 获得超0个赞
我不使用模板逻辑,而是将逻辑移到类中。
cart并且products显然在课堂上可用。因此调整类中的函数以根据需要返回产品列表(带有数量信息)并在模板中fetchProducts使用单个循环。ngFor
或者添加一个新功能getProductsWithQuantity...
在你的课上
public getProductsWithQuantity() {
return this.fetchProducts().map(product => {
...product,
quantity: this.getQuantity(product);
});
}
private getQuantity(product) {
const foundCartItem = this.cart.find(cartItem => product.id === cartItem.id);
if (foundCartItem) {
return foundCartItem.qty;
}
return 0;
}
在您的模板中:
<ion-item class="added" *ngFor="let item of getProductsWithQuantity();let key=index;">
<span class="count">
{{item.qty}}
</span>
...
添加回答
举报