angular - 使用 Angular 6 ngFor,如何在与其他数据数组比较时更改一些内容?
问题描述
我正在创建购物车。我有产品数据的对象数组和购物车项目数据的数组。我尝试构建按钮来购买商品,具有条件按钮,如果购物车数据中的相同产品则需要显示“+ 3 -”(数量来自 Id 的购物车数据),如果产品不在购物车中,则只需显示“购买”按钮. 我在https://stackblitz.com/edit/angular-267ern上实现了这个相关问题。
我尝试解决:
- 管道,
- 追踪,
- 尝试更改产品数组数据映射并返回与购物车数据比较的值(这是为了尝试获得解决方案,但我做不到)。这里 bu 使用管道可能在复杂性(n * 2)方面存在一些问题。
因此,寻找复杂性更低的解决方案,至少解决这个问题。如果可能,请注意复杂性。
解决方案
我想我理解你的问题,这是你想要的吗?
在 TS 中(从 stackblitz 复制)
export class AppComponent {
products :product[]= [
{ name: 'Radio', price: 34, _id: '12345' },
{ name: 'TV', price: 44, _id: '12346' },
{ name: 'Bascket', price: 16, _id: '12347' },
{ name: 'Banana', price: 4, _id: '12348' },
{ name: 'Bike', price: 5000, _id: '12349' },
{ name: 'Toast', price: 5, _id: '12350' },
{ name: 'Shirt', price: 17, _id: '12351' }
];
isCart (id){
return this.cart.findIndex((x)=>x._id == id)>=0;
}
quantity(id){
return this.cart.find((x)=>x._id == id).quantity;
}
buy(prod:product){
if(this.cart.findIndex((x)=>x._id == prod._id)<0){
this.cart.push({name:prod.name,price:prod.price,_id:prod._id,quantity:1})
}else{
let prod1 = this.cart.find((x)=>x._id == prod._id);
prod1.quantity +=1;
}
}
cart = [
{ name: 'Radio', price: 34, _id: '12345', quantity: 5 },
{ name: 'Toast', price: 5, _id: '12350', quantity: 1 },
]
}
export interface product{
name:string;
price:number;
_id:string;
}
在 HTML 中:
<label *ngFor="let item of products">
<span>
<p>Name: {{item?.name}}, Price: {{item?.price}}</p>
</span>
<button (click)="buy(item)">
<span>{{isCart(item._id)?quantity(item._id)+'-':'Buy'}}
</span>
</button>
</label>