Reputation: 690
I am new in ionic 4. I am doing shopping cart function. I want to delete the selected item. But it delete like pop function not delete the certain item. I have follow this tutorial : https://devdactic.com/dynamic-ionic-4-slides/
In service ts I am using this function then Cart.page.ts
onDeleteItem(i) {
const index = this.selectedItems.indexOf(i);
if (index > -1) {
this.cartServ.deleteFromCart(i);
this.selectedItems.splice(index, 1);
console.log(this.selectedItems);
}
this.total = this.selectedItems.reduce((a, b) => a + (b.count * b.price), 0);
}
Cart.service
addToCart(product) {
this.cartService.addProduct(product);
}
deleteFromCart(i) {
const index = this.cart.indexOf(i);
if (index > -1) {
this.cart.splice(index, 1);
}
}
Anyone can help me?
Upvotes: 1
Views: 529
Reputation: 5265
Don't pass the index
to deleteFromCart
function.
The reason is index
of the deleting item in selectedItems
array may not be the same index in cart
items Array.
Pass the i
which is the item, to deleteFromCart
function and find the index
and use splice
.
onDeleteItem(i) {
...
this.cartServ.deleteFromCart(i);
...
}
deleteFromCart(i) {
const items = this.cart.filter(item => item.id === i.id);
const index = this.cart.indexOf(items[0])
if (index > -1) {
this.cart.splice(index, 1);
}
}
Upvotes: 2