【发布时间】:2021-04-13 07:22:06
【问题描述】:
每次我添加相同的商品时,我都会尝试创建一个购物车,它会为我创建一个新行, 我想更新 Quantity,是否必须创建一个遍历数组的循环?
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>
【问题讨论】:
-
为什么?看来您的代码有效。你有什么问题?
-
问题是每次我添加相同的项目时它都会为我创建一个新行而不是更新数量
标签: javascript angular typescript cart shopping