每次添加相同的商品时,我都会尝试创建一个购物车,它会为我创建一个新行,我想更新数量,我是否必须制作一个穿过数组的循环?
ts.file
productList = [
{ id: 1, name: 'Louis Vuis', price: 10, qtn: 1 },
{ id: 2, name: 'shubert helmet', price: 20, qtn: 1 },
];
productArray: any = [];
add(product) {
this.productArray.push(product);
}
inc(added) {
added.qtn = added.qtn + 1;
}
dec(added) {
if (added.qtn != 1)
added.qtn -= 1;
}
remove(id) {
this.productArray.splice(id, 1);
}
}
html
<div class="card" *ngFor="let product of productList">
<h1>{{product.name}}</h1>
<p class="price">{{product.price | currency: 'USD'}}</p>
<p><button (click)="add(product)">Add to Cart</button></p>
<th>product</th>
<th>price</th>
<th>Quantity</th>
<th>Delete</th>
<th>total</th>
</tr>
</thead>
<tbody *ngFor="let added of productArray">
<tr>
<td>{{added.name}}</td>
<td>{{added.price | currency: 'USD'}}</td>
<td class="increment">
<button (click)="dec(added)">-</button>
<span>{{added.qtn}}</span>
<button (click)="inc(added)">+</button>
</td>
<td (click)="remove()"><strong class="remove">X</strong></td>
您可以将add(product)
更改为:
add(product, idx) {
const found = this.productArray.find(
item => JSON.stringify(item) === JSON.stringify(product)
);
if (found) {
this.productArray[idx].qtn++;
} else {
this.productArray.push(product);
}
}
在这里,它将搜索类似的产品(我不知道哪个是唯一性标准,所以我将整个对象与添加的新对象进行了比较(,如果找到了,它将更新数量,否则它将推送新产品。
HTML部分:
<div class="card" *ngFor="let product of productList; let idx = index"> // <-- here
<h1>{{product.name}}</h1>
<p class="price">{{product.price | currency: 'USD'}}</p>
<p><button (click)="add(product, idx)">Add to Cart</button></p> // <-- & here
演示
问题来自:
add(product) {
this.productArray.push(product);
}
您推送相同的项目,并在数组中创建一个新对象。你可以通过检查这个项目是否存在来修复它:
add(product) {
for(let singleProduct of productList){
if(singleProduct.name === product.name){
//here you want to only increase the quantity of this product
//it will look like this:
singleProduct.qtn += 1
} else {
productArray.push(product);
}
}