One press sets off a chain reaction of unintended consequences

I am facing an issue where I want to implement functionality to modify the quantity of a selected product using two buttons: minus and plus. Strangely, when clicking the plus button it also triggers the click event of the minus button. Can anyone shed light on why this might be happening? Appreciate your help!

  let productQuantity = 1;

  constructor() { }

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

  modifyProductQuantity(){
    let decreaseBtn = document.querySelector('#minus') as HTMLElement;
    let increaseBtn = document.querySelector('#plus') as HTMLElement;

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

     increaseBtn.onclick = () => {
      productQuantity++;
     };
   }

Answer №1

Using event binding in Angular makes handling events much simpler.

Give this a shot:

Template.html

<button (click)="increaseQuantity"> + </button>
<button (click)="decreaseQuantity"> - </button>

Component.ts

currentAmount = 1;

increaseQuantity() {
   this.currentAmount++;
}

decreaseQuantity() {
   if (this.currentAmount > 1) {
      this.currentAmount--;
   }
}

Learn more about Angular Event binding here

Answer №2

Without a clear view of your HTML structure, it can be difficult to pinpoint the issue. However, it is likely related to a phenomenon known as "event bubbling."

To resolve this, consider changing your onclick function to:

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

For a more detailed explanation of this concept, you can visit:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to Load CSS in New Magento Template

I have reached out to the template creator's website and Magento support for assistance, unfortunately, I have not received any response so far. Despite installing a custom theme that is said to be compatible with the latest version of Magento, the C ...

Enhance your angular application with universal support using the CLI for Angular 6

After creating a new Angular6 application using Angular CLI, I used the following command: ng generate universal This added support for Universal rendering. Everything is working fine, but I noticed that it also added the following code to my angular.jso ...

Oops! Looks like we encountered an issue: Unable to locate a differ compatible with the object '[object Object]' of type 'object'. NgFor can only bind to Iterables in

Greetings everyone, I am facing an issue with the following error message: ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables I have attempted using .json bu ...

Surprising property quirks in TypeScript classes

I am developing a TypeScript game and encountered an issue while creating a player class. The error I'm getting is: Property 'playerInformation' does not exist on type 'Player' Here is the code snippet: export default class Player ...

Ways to stylize bullet points in lists with CSS in HTML document

I am currently working on a Q&A page using simple HTML. This is the current appearance of my page. Check it out here on JSFIDDLE. My task involves adding an 'A' to the answer for each question. Some answers have multiple paragraphs, so the ...

Prevent the shifting of website elements when zooming in or out

As a beginner in HTML/CSS, I am trying to ensure that my content stays in place when zooming in/out or resizing the window. Initially, everything was centered, but after adding position:absolute to the outermost div, the alignment shifted slightly to the l ...

What causes a CSS class to have priority over another?

I've encountered a challenge in my Vue.js project where I'm utilizing Vuetify and vue-flash-message. My goal is to change the warning message background to 'blueviolet' by adjusting its style: .flash__message.warning { color: #ffffff ...

Insert numerous records into a database table using razor CSHTML

I have been attempting to code in VS2012 to enable the input of a username, selection of project checkboxes within a table, and submission. The goal is for each project to be inserted into a database table alongside that username. Despite my efforts, I am ...

Can you explain the distinction between setting abc.p as undefined versus deleting abc.p?

The variable abc is pointing to an object. What distinguishes abc.p = undefined from delete abc.p aside from their return values? ...

Hide the first div within the inner div of a section using CSS

I am working on a section that contains multiple nested divs. Within each outer div, there are 3-4 inner divs. My goal is to hide only the first inner div of each outer div while still displaying some text. section div div:nth-child(1){ display: n ...

Issues with tabs functionality in Bootstrap version 4.3.1, unlike the smooth operation in v4.1.0

I encountered an interesting situation recently. After spending almost 3 hours troubleshooting my code, I discovered that it functions perfectly on Bootstrap v4.1.0 but fails on the latest version, v4.3.1. Working JSFiddle with Bootstrap v4.1.0: https://j ...

Prevent Form Submission in Microsoft Edge

I need help figuring out how to prevent Microsoft Edge from keeping form values, such as inputs, when a page refreshes. You can see the issue by looking at the first name last name example on this page https://www.tutorialspoint.com/html/html_forms.htm. ...

Creating unique ID tags using AngularJS

I am struggling with creating an HTML structure that looks like this: <ul> <li id="r1_1">Root node 1 <ul> <li id="child_node_1">Child node 1</li> <li id="child_node_2">Child node 2</ ...

Waiting for Observable in constructor of Angular service

My Angular 2 service contains the following constructor: constructor(public fireAuth: AngularFireAuth) { console.log('1'); fireAuth.authState.subscribe(user => { console.log('2'); this.user = user; }) ...

The JSON object cannot be assigned to the IntrinsicAttributes and customType data types

Currently, I'm facing a challenge with reading JSON data into an array of type pinImage. My goal is to loop/map through my pinImage objects and pass each one to a child component called PinCard, which is specifically designed to accept an object of ty ...

Parsing HTML with a simple DOM parser

I am utilizing the simple php dom parser in my project. Within my loaded dom, there is a link that appears like this in html: <a href="...">Some const tesxt</a> I am wondering how I can utilize the find function to select this particular obje ...

Issue: The provider specified for the NgModule 'AppModule' is invalid - it should only be instances of Provider and Type, but instead received: [?[object Object]?, ...]. This error occurred within Ionic framework

While working on my IONIC project, I encountered an error when adding Geolocation to my providers. Removing it from the providers allows my app to function properly, but even my professor couldn't solve the issue. Here is the content of my file: impor ...

Position the image between two div containers in the center of the screen, ensuring it is responsive and does not overlap with any text

I've been working on trying to position an image between two divs on my webpage. So far, I've managed to place the image there but it's not responsive (only displays correctly at a width of 1920) and ends up overlapping the text in both divs ...

What's the best way to place the text or operator from a button into an input field?

Hello, I am currently working on developing a calculator. However, I have encountered an issue where clicking on operator buttons such as +, -, /, *, and the dot button does not add them to my input field. Additionally, when these buttons are clicked, the ...

Ways to trigger the keyup function on a textbox for each dynamically generated form in Angular8

When dynamically generating a form, I bind the calculateBCT function to a textbox like this: <input matInput type="text" (keyup)="calculateBCT($event)" formControlName="avgBCT">, and display the result in another textbox ...