How to dynamic quantity + and - in ionic 2?

203 Views Asked by At
<p><b>Qty :</b>
    <ion-icon name="remove-circle" (click)="decrement()"></ion-icon>
      {{cart.qty}}
    <ion-icon name="add-circle" (click)="increment()"></ion-icon>
 </p>

Here is cart.ts code

ionViewDidLoad() {
        var param = "user_id=" + this.user_id;
        this.UtilsService.makeAPICall(this.UtilsService.postMethod, 
          this.UtilsService.CartItemAPI, param, (response) => {
          if(response.data)
          { 
            this.Data = response["data"];
            this.Qty = response["qty"];
            localStorage.setItem("qty", this.Qty);
          }  
        });
      }

How to + and - quantities in that code?

1

There are 1 best solutions below

1
On

There's a lot of ways to do this, but since you're saving the quantity in your localStorage having a method to do this is the best way. So in your .ts file you'll have

decrement = () => {
  // you don't want it to decrement to lower than 0
  if (this.Qty > 0 ) {
    this.Qty -= 1;
    localStorage.setItem("qty", this.Qty);
  }
}

increment = () => {
  this.Qty += 1;
  localStorage.setItem("qty", this.Qty);
}

Also you can't access it with {{cart.qty}}, you need {{Qty}} instead.

If you don't need to save it all the time in the localStorage you can do it inline in your HTML

<p><b>Qty :</b>
  <!-- checking if it's 0 before removing 1 from the total quantity -->
  <ion-icon name="remove-circle" (click)="Qty = Qty > 0 ? Qty - 1 : Qty"></ion-icon>
      {{Qty}}
  <ion-icon name="add-circle" (click)="Qty += 1"></ion-icon>
</p>

Hope this helps.