Search code examples
arraysangularsplice

Unable to remove items using splice within for loop in Angular


I am trying to remove an item from an existing array using splice but is not working as expected. I even tried using filter instead of splice but got the same output. Can some one please take a look at the functionality here and help me figure out the issue.

Please try to add the available items here - https://08b11a0437.stackblitz.io/products then navigate to the cart page and try to remove each item. The items are not getting removed as expected.

Relevant Code is available in cartservice.ts, cartcomponent.ts(removeProductFromCart()) and cartcomponent.html - https://stackblitz.com/edit/08b11a0437?file=app%2Fcart%2Fcart.component.ts


Solution

  • The problem is you are removing items from an array in cartService, but for the UI you are using values from the products array.

    A quick fix is to reload your products array. Just add the following code in your removeProductFromCart function in ShoppingCartComponent. Add it at the end of the function.

    this._cartService.getAddedProducts().subscribe((data: IProduct[]) => {
      this.products = data.map(item => item[0]);      
    });   
    

    Apart from that there is another issue. You are hiding items in ShoppingCartComponent html using *ngIf="removeItemId !== product.id". Consider you have three products (with id 1,2 and 3) in your cart, when the first products is removed, removeItemId will have 1, so the first product will be hidden. But when the user removes the second product, removeItemId will be set to 2, and now product one will be visible.