0

I want to modify the quantity of the selected product with 2 buttons: minus and plus. Clicking the minus button works as expected but clicking the plus button also triggers the minus buttons' click event.

Any idea why? Thank you!

  productQuantity = 1;

  constructor() { }

  ngOnInit(): void {
    this.modifyQuantity();
  }

  modifyQuantity(){
    let minusBtn = document.querySelector('#minus') as HTMLElement;
    let plusBtn = document.querySelector('#plus') as HTMLElement;

     minusBtn.onclick = () => {
        if(this.productQuantity > 1){
         this.productQuantity--;
       }
      };

     plusBtn.onclick = () => {
      this.productQuantity++;
     };
   }

2 Answers2

2

In angular it's easier with event binding

You can try this :

Component.html

<button (click)="plus"> + </button>
<button (click)="minus"> - </button>

Component.ts

productQuantity = 1;
  plus() {
   this.productQuantity++
}

minus() {
if(this.productQuantity > 1){
this.productQuantity--
}
}

Angular Event binding

Ali BEN AMOR
  • 126
  • 1
  • 6
0

It's hard to figure out because we can't see your HTML structure. But this is probably happening because of a concept called "event bubbling".

In short the solution would be to change your onclick function to:

(e) => {
  e.stopPropagation();
  if(this.productQuantity > 1){
    this.productQuantity--;
  }
};

This concept is explained more in depth here: https://stackoverflow.com/a/4616720/4796342

Bram
  • 444
  • 1
  • 5
  • 18