I am attempting to implement a feature in Angular that prevents double clicking on buttons using directives.
Below is the pertinent code snippet from my template:
<button (click)="onClickFunction()" appPreventDoubleClick>Add</button>
And here is the directive I have defined for this purpose:
@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);
}
}
}
The main goal here is to disable a button if it is clicked twice and then re-enable it after one second to prevent onClickFunction()
from being triggered while the button is disabled. However, I am facing an issue where even though the @HostListener click()
function runs before onClickFunction()
, the latter still executes. How can I resolve this? Any assistance would be greatly appreciated.
Edit: In response to a comment, I must note that initially, I tried the following approach:
@HostListener("click", ["$event"])
click(event) {
event.srcElement.setAttribute("disabled", true);
setTimeout(() => {
event.srcElement.removeAttribute("disabled");
}, 1000);
}
However, this method has a drawback as the button may get disabled before the first invocation of the function. I am seeking a more universal solution that works consistently across different scenarios. Could someone explain why this inconsistency happens and provide suggestions for rectifying it? Your input is highly valued. Thank you in advance.