3

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>
3
  • 1
    Is your JS code in a controller? How is your controller being included in your view? Commented May 7, 2016 at 23:46
  • Yes! it is outside of the constructor() Commented May 7, 2016 at 23:49
  • 3
    Btw, even if the current code worked, it would always increment/decrement the amount by 2, since you're using post-increment (the ++) before console.log and also within the console.log statement. Commented May 8, 2016 at 0:17

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Your solution does not work if we have duplicate buttons... it will keep incrementing/decrementing all the other buttons together

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.