-1

I am trying to add no. of quantity for a product using angular 12 but when i clicked on add button but its adding for all products like shown in image. screenshot of issue

HTML Code

 <div class="card-content">
    <h3 class="title">{{food.FoodName}}</h3>
    <h2 class="subtitle">{{food.Rate | currency:"INR"}}</h2>

    <div class="actions">
      <ion-buttons>
        <ion-button (click)="addtoCart(food)">
          <ion-icon slot="icon-only" name="add"></ion-icon>
        </ion-button>
        <div class="counter" style="font-size: 2rem">{{quantity}}</div>
        <ion-button (click)="removeCart(food)">
          <ion-icon slot="icon-only" name="remove"></ion-icon>
        </ion-button>
      </ion-buttons>
    </div>
  </div>

TS Code

quantity: number = 0;

addtoCart(food: any) {        
    this.quantity++;
    console.log(food);
 }
chethan
  • 42
  • 10
  • I'm assuming the html is in an `ngFor`, is that corrrect? If so all your food items reference the same `quantity` property so when it changes they all change. Put the quantity on the food object itself so you can maintain a quantity for each food item. – Jason White Oct 17 '21 at 12:24
  • @Jason White yes HTML is in `ngFor`. You mean to have one more property called quantity inside Food object itself ?? – chethan Oct 17 '21 at 12:31
  • Yes, if you want to maintain a quantity count for each item. Or you could create a separate component and pass the food object down to the child component and the child component will have the quantity property. – Jason White Oct 17 '21 at 12:34
  • Yes thanks got the solution – chethan Oct 17 '21 at 12:45

1 Answers1

1

You are using a single variable to store the quantity. This won't store it for all items. You need to add the quantity in the food object itself so that each food item has its own quantity in the list.

Note: It's better to add quantity property to each food object when you fetch/add to the list of food items. The below code would work with the current situation though:

addtoCart(food: any) { 
     if(food.quantity){ // if quantity already exists on food object
       food.quantity++;
    }else{
    food.quantity=1;//if quantity does not exist on food object, add it
    }
    console.log(food);
 }

Changes in HTML: Assuming that you are looping through multiple food objects, display the quantity of that particular food.

<div class="counter" style="font-size: 2rem">{{food?.quantity || 0}}</div>
Pankaj Sati
  • 2,441
  • 1
  • 14
  • 21
  • 1
    For the html you'll probably have to do a null check for the quantity `{{ food?.quantity || 0 }}` if you're adding the quantity property on `addtoCard`. – Jason White Oct 17 '21 at 12:38