Disable element attribute before onclick function

2019-08-02 00:02发布

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条回答
手持菜刀,她持情操
2楼-- · 2019-08-02 00:39

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.

查看更多
登录 后发表回答