首页 > 解决方案 > Angular 9按钮单击多次触发

问题描述

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');
   }

当我多次单击按钮(名为 click me)时,console.log 会打印多次。无论点击次数如何,如何使其仅在第一次调用?

我尝试了 event.preventdefault(),但出现以下错误:

Cannot read property 'preventDefault' of undefined

任何建议将不胜感激。

标签: javascriptangular

解决方案


您可以创建一个计数器来跟踪点击次数并保护点击方法。

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');
}

推荐阅读