I try to do a shopping cart each time I add the same item it creates a new line for me, I would like to update the Quantity, do I have to make a loop that goes through an array?
ts.file
JavaScript
x
25
25
1
productList = [
2
{ id: 1, name: 'Louis Vuis', price: 10, qtn: 1 },
3
{ id: 2, name: 'shubert helmet', price: 20, qtn: 1 },
4
];
5
6
productArray: any = [];
7
8
add(product) {
9
this.productArray.push(product);
10
}
11
12
inc(added) {
13
added.qtn = added.qtn + 1;
14
}
15
16
dec(added) {
17
if (added.qtn != 1)
18
added.qtn -= 1;
19
}
20
21
remove(id) {
22
this.productArray.splice(id, 1);
23
}
24
}
25
html
JavaScript
1
23
23
1
<div class="card" *ngFor="let product of productList">
2
<h1>{{product.name}}</h1>
3
<p class="price">{{product.price | currency: 'USD'}}</p>
4
<p><button (click)="add(product)">Add to Cart</button></p>
5
6
<th>product</th>
7
<th>price</th>
8
<th>Quantity</th>
9
<th>Delete</th>
10
<th>total</th>
11
</tr>
12
</thead>
13
<tbody *ngFor="let added of productArray">
14
<tr>
15
<td>{{added.name}}</td>
16
<td>{{added.price | currency: 'USD'}}</td>
17
<td class="increment">
18
<button (click)="dec(added)">-</button>
19
<span>{{added.qtn}}</span>
20
<button (click)="inc(added)">+</button>
21
</td>
22
<td (click)="remove()"><strong class="remove">X</strong></td>
23
Advertisement
Answer
You can change your add(product)
to:
JavaScript
1
11
11
1
add(product, idx) {
2
const found = this.productArray.find(
3
item => JSON.stringify(item) === JSON.stringify(product)
4
);
5
if (found) {
6
this.productArray[idx].qtn++;
7
} else {
8
this.productArray.push(product);
9
}
10
}
11
Here it will search for a similar product (I dont know which was the unicity criteria, so I compared the whole object with the whole new added one), If it’s found, it would update the quantity, else it push a new product.
And the HTML part:
JavaScript
1
5
1
<div class="card" *ngFor="let product of productList; let idx = index"> // <-- here
2
<h1>{{product.name}}</h1>
3
<p class="price">{{product.price | currency: 'USD'}}</p>
4
<p><button (click)="add(product, idx)">Add to Cart</button></p> // <-- & here
5