Disable element attribute before onclick function is executed

断了今生、忘了曾经 提交于 2019-12-11 06:02:25

问题


I am trying to disable double clicking buttons using directives in Angular.

Here is my relevant template code:

<button (click)="onClickFunction()" appPreventDoubleClick>Add</button>

Here is my directive:

@Directive({
  selector: "[appPreventDoubleClick]"
})
export class PreventDoubleClickDirective {
  count: number = 0;
  constructor() {}

  @HostListener("click", ["$event"])
  click(event) {
    ++this.count;
    if (this.count > 1) {
      console.log("disabling");
      event.srcElement.setAttribute("disabled",true);
      setTimeout(() => {
        event.srcElement.removeAttribute("disabled");
        this.count = 0;
      }, 1000);
    }
  }
}

What I'm basically trying to do is disable a button if it's clicked twice and reset it after 1 second so that onClickFunction() won't be called if it is disabled. But what's happening is that although the @HostListener click() function is being called before onClickFunction(), onClickFunction() is still executing. How can I solve this problem? Any help is appreciated.

Edit: As per the comment, I wanted to mention that I had tried this first:

@HostListener("click", ["$event"])
click(event) {
  event.srcElement.setAttribute("disabled", true);
  setTimeout(() => {
    event.srcElement.removeAttribute("disabled");
  }, 1000);
}

But this works on a case-by-case basis, as in some cases the button is disabled even before the function is called the very first time. I want to find a generic solution that works everywhere. Can anyone tell me why this mismatch occurs, and what I can do to fix this? Thanks in advance.


回答1:


Alright. I found a solution for this issue. Here is my directive with the updated code.

@Directive({
  selector: "[appPreventDoubleClick]"
})
export class PreventDoubleClickDirective {
  constructor() {}

  @HostListener("click", ["$event"])
  click(event) {
    setTimeout(() => {
      event.srcElement.setAttribute("disabled", true);
    }, 0);
    setTimeout(() => {
      event.srcElement.removeAttribute("disabled");
    }, 1000);
  }
}

I'm not exactly sure why this works, hope some of you have a better understanding.



来源:https://stackoverflow.com/questions/53495454/disable-element-attribute-before-onclick-function-is-executed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!