Search code examples
angulartypescriptngfor

angular9 ngfor removing object from array shows undefined error


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


Solution

  • 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);