Hey there, I have a little dilemma with my shopping cart system. I can easily add and delete products using an API. However, when it comes to deleting an item from the cart, I have to do it one by one by clicking on a button for each item, which is not very efficient. I've been trying to figure out a way to empty the entire cart at once from a function, rather than having to click on each item individually, but haven't had any luck so far as the ID becomes undefined.
My main question is whether this is even possible. I've attempted to clear the array of items by setting cartItems.length = 0 or cartItems = [], but from what I understand, this only clears a copy of the array, leaving the items still present in the cart.
I'm hoping someone can provide some insight and guide me in the right direction. Your help would be greatly appreciated. I've included a snippet of HTML and the cart service code for deleting an item below.
Cart Service
RemoveProductFromCart(id:number):Observable<void>{
return this.http.delete<CartItem[]>(`${this.cartUrl}/${id}`)
.pipe(catchError(_err => of (null))
);
}
CartItem.ts
handleRemoveFromCart(){
alert("hit remove from cart");
this.cartService.RemoveProductFromCart(this.cartItem.id)
.subscribe(() =>
console.log("Product with Id deleted",
this.cartItem.id),
(err) => console.log(err)
);
}
HTML for Cart Item
<div class="container-md" >
<div>
<img class="img-fluid" [src]="cartItem.imageUrl" style="padding-bottom:5px; padding-top:50px" alt="Cart">
<div class="text-nowrap" style="font-size:13px; width: 400px">{{cartItem.productName}}</div>
{{cartItem?.size}}{{Valuesize}}
<div style="font-size:13px"><strong>{{ (cartItem.price) | currency}}</strong></div>
<div class=" float-right">
<span><i class="fa-solid fa-trash-can" style="color:#D30169; cursor: pointer;" (click)="handleRemoveFromCart();handleReload()"></i></span>
</div>
</div>
</div>
Cart HTML
<div *ngIf="cartItems.length === 0"class="alert alert-info">Your Cart is Empty</div>
<div *ngIf="product">
<div>{{product.name}}</div>
<input type="number" [(ngModel)]="product.num"
min="0"/>
</div>
<div *ngFor="let item of cartItems; let i = index">
<app-cart-item [cartItem]="item"></app-cart-item>
</div>
<li class="list-group-item" style="margin-top:30px">
<strong>Total Items {{itemTotal}}</strong>
</li>
<li class="list-group-item active">
<strong>Total: {{ cartTotal | currency}}</strong>
</li>
<li class="btn btn-primary" style="height: 40px;
width:210px; margin-top:20px; color:ffffff">
<a class="" routerLink="/clothing" style="color:
#ffffff; cursor: pointer">Continue
Shopping</a>
</li>
<li class= "btn" style="height: 40px; width:210px;
margin-top: 20px; background-color:#D30169">
<a class="" routerLink="/checkout" style="color:
#ffffff">Go To Checkout</a>
</li>
</div>
</div>
</div