Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2/JavaScript - Increment/Decrement by 1 on (click)

I want to Increment/Decrement when the user presses the add button, then update the amount value accordingly. I've tried a couple of times, but unfortunately I was not successful!

Here is the code:

  addToCart(){
  this.amount = 1;
  }

  addItem(){
    this.amount++;
    console.log('plus is : '+this.amount++)
  }

  removeItem(){
   this.amount--;
   console.log('plus is : '+this.amount--)
  }

HTML:

   <div (click)="addToCart()">ADD</div>
   <div (click)="removeItem()" class="btnSign">-</div> 
   <div>{{amount}}</div> 
   <div (click)="addItem()" class="btnSign">+</div>
like image 334
Folky.H Avatar asked Feb 12 '26 09:02

Folky.H


1 Answers

The mistake was in using ++

export class HelloWorld {
public amount:number;

addToCart(){
this.amount = 1;
}

addItem(){
this.amount=this.amount+1;
console.log('plus is : '+this.amount)
}

removeItem(){
this.amount=this.amount-1;
console.log('plus is : '+this.amount)
}


}

here is the plunker

like image 144
KB_ Avatar answered Feb 14 '26 18:02

KB_



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!