1

I have an array of items which are objects. The items are called from a service and shown when I go on the cart page.

When I click the remove button I run delete this.cart.items[i];. this.cart is my service, and removes the item from the object. It successfully does this on the page too but I then get a blank element and errors in console saying Cannot read property 'qty' of undefined. I assumed the ngfor will auto update the the DOM and remove the element as that object no longer exists. Would I also have to remove the element from the DOM manually?

from the array below, I wanted to remove the first item completely but still show the second.

[
  {
    "desc": "Description",
    "item": "item 1",
    "id": "1",
    "portion": "small",
    "price": "4.25",
    "qty": 3
  },
  {
    "desc": "Description",
    "item": "item 2",
    "id": "2",
    "portion": "large",
    "price": "4",
    "qty": 1
  }
]


<div class="cart-item" *ngFor="let item of items" (click)='ontap(item);'>
    {{ x.item }}
</div>

this is where I display it, but it still shows the elemnt with no data. Thanks

2
  • can you share some code ? Commented Aug 23, 2020 at 20:35
  • have you try to remove an item like this this.cart.items.splice(i,1); Commented Aug 23, 2020 at 20:45

3 Answers 3

2

Use ngFor with index to get the index on your button click:

<div class="cart-item" *ngFor="let item of items; let i = index" (click)='onRemove(i);'>
    {{ x.item }}
</div>

Then use that index to remove from array and reassign the resulting array to itself:

onRemove(index: number) {
   this.items = [...this.items.splice(index, 1)]
}

NOTE: The spread operator is used to trigger the change detection on Angular.

Sign up to request clarification or add additional context in comments.

Comments

1

this delete this.cart.items[i] is not the correct way to remove an element from an array the delete statement remove the item but still the length of the array is the same

this.cart.items.splice(i,1);

Comments

1

If you are using onPush strategy with your dumb component then the value in DOM will not update.

You have to write it like this e.g:

let itemsWithoutRemoved = this.cart.items.splice(i, 1);

this.cart = {
...this.cart,
items: itemsWithoutRemoved 
}

Then your view will update as the Input has changed.

Also, removing an item from array is done via splice method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.