Billy
Billy

Reputation: 905

Angular 9 button click firing multiple times

Html

<button (click)="myClickFunction($event)">
   Click Me
</button>

app.component.ts

myClickFunction(event) { 
      //just added console.log which will display the event details 
      console.log('inside myClickFunction');
   }

When I click on the button (named click me) multiple times, the console.log is printing multiple times. How to make it call only the first time irrespective of number of clicks?

I have tried event.preventdefault(), but getting following error:

Cannot read property 'preventDefault' of undefined

Any suggestion will be appreciated.

Upvotes: 2

Views: 4670

Answers (2)

Afshin Mobayen Khiabani
Afshin Mobayen Khiabani

Reputation: 1269

Eko's Answer is correct but as you want the function to run only once it would be better to use Boolean instead.

private isClicked = false;

myClickFunction(event) { 
  if(this.isClicked){
    return;
  }
  this.isClicked = true;
  //just added console.log which will display the event details 
  console.log('inside myClickFunction');
}

Or you can disable the button in the function after click.

Upvotes: 1

eko
eko

Reputation: 40647

You can create a counter to track the number of clicks and guard the click method with respect to that.

private clickCounter = 0;

myClickFunction(event) { 
  if(this.clickCounter > 0){
    return;
  }
  this.clickCounter++;
  //just added console.log which will display the event details 
  console.log('inside myClickFunction');
}

Upvotes: 2

Related Questions