Prevent the element attribute from being enabled before the onclick function is triggered

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.

Answer №1

Great news! I've managed to solve the issue at hand. Below you'll find my directive with the updated code implementation.

@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 don't have a full explanation for why this solution works, but hopefully some of you can shed some light on it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 5 does not recognize the function submitEl.triggerEventHandler, resulting in an error

Greetings! I am currently working on writing unit test cases in Angular5 Jasmine related to submitting a form. Below is the structure of my form: <form *ngIf="formResetToggle" class="form-horizontal" name="scopesEditorForm" #f="ngForm" novalidate (ngSu ...

Is the Prisma model not reachable through Prisma Client?

I'm currently attempting to retrieve a specific property of a Prisma model using Prisma Client. The model in question is related to restaurants and includes a reviews property that also corresponds with a separate Review model. schema.prisma file: // ...

Issue with rendering Base64 image array strings in FlatList component in React Native

In my RN App, I am trying to display a FlatList with Image Items but it seems like I have missed something. I am retrieving blob data from my API, converting it to a String using Buffer, and then adding it to an Array. This Array is used to populate the F ...

Issue with the exported elements known as 'StatSyncFn'

My build is showing an error that I'm unable to identify the source or reason for. The error message looks like this... Error: node_modules/webpack-dev-middleware/types/index.d.ts:204:27 - error TS2694: Namespace '"fs"' has no expo ...

Develop an interface in TypeScript for intricate data structures

Displayed below is a variable that contains a collection of objects: scenes = { sky: { image: 'assets/1.jpg', points: { blue_area: { x: 1, y: 2 }, } }, blue_area: { image: & ...

Development in Angular 2 with a team of developers utilizing TFVC for version control and managing node_modules

With over 20,000 files in the node_modules directory, it may not be practical to include them in source control. This results in developers having to run 'npm install' every time they perform a 'get latest' in order to download any mis ...

Issue with displaying tab icons in Ionic 4

After updating the versions of Angular, Cordova, and Ionic, I started experiencing an issue with the tab icons displaying partially. Specifically, when my app loads with 4 tabs, only the first and third icons are visible. However, upon touching one of the ...

Ways to update index.html in Angular 8.3+ based on the current environment settings

I am currently developing an application using jhipster, Spring Boot, and Angular. One challenge I am facing is setting up different public keys based on whether the app is running in a development or production environment. I have spent a considerable a ...

What is the best way to handle various sections with changing structures within a complex form using react-hook-form?

I am working on a complex form that has sections A, B, and C, each of which can be in shape A1 or A2, B1 or B2, C1, or C2. Users are required to fill out settings based on whether the section is set to "advanced" or "basic". I want users to submit the enti ...

Incorporating a Symbol into a Function

Reviewing the following code snippet: namespace Add { type AddType = { (x: number, y: number): number; }; const add: AddType = (x: number, y: number) => { return x + y; }; } Can a 'unique symbol' be added to the AddType lik ...

Implementing a video pause event trigger from a function in Angular2

Here is the content of my player.component.html: <video width="320" height="240" autoplay autobuffer [src]="videoSrc" (ended)="videoEnd()"> Your browser does not support the video tag. </video> <button (click)="pauseOrPlay()">pause/play ...

Encountered an issue while attempting to authenticate CMS signature using pkijs

I am attempting to validate a CMS signature generated with open ssl using the following command: $ openssl cms -sign -signer domain.pem -inkey domain.key -binary -in README.md -outform der -out signature Below is my code utilizing pkijs: import * as pkij ...

What is the trick to accessing an object's key and value when you are unsure of the object's

Currently, I am in the process of constructing a React component that is designed to receive an array of objects. However, I have encountered a question: Is there a way for me to retrieve both the key and value of an object within the map function without ...

Tips for bypassing the 'server-only' restrictions when executing commands from the command line

I have a NextJS application with a specific library that I want to ensure is only imported on the server side and not on the client side. To achieve this, I use import 'server-only'. However, I also need to use this file for a local script. The i ...

Customizing date colors in JavaScript: A step-by-step guide

var active_dates1 = ["2017-04-02 00:00:00","2014-04-03 00:00:00","2014-04-01 00:00:00"]; $('.datePick', this.$el).datepicker( beforeShowDay: function (date) { for(let date1 of active_dates1){ if (date.getTime( ...

Can you explain how this promise functions within the context of the mutation observer, even without an argument?

Recently, I came across a mutation observer in some TypeScript code that has left me puzzled. This particular implementation of a promise within the mutation observer seems unconventional to me: const observer = new MutationObserver((mutations: MutationR ...

Is it possible to create a development build using Npm with React and Typescript?

I have successfully set up a TypeScript React app by using the command below: npx create-react-app my-app --template typescript However, running "npm start" generates development javascript files and launches a development server which is not id ...

transmit URL parameters to Express using Angular 2

I have implemented an Angular service to retrieve data from Express: getRestaurants(districtId) : Observable<void[]>{ let params: URLSearchParams = new URLSearchParams(); params.set('id', districtId); return this.http.get(this.url, ...

Creating objects based on interfaces in TypeScript is a common practice. This process involves defining

Within my TypeScript code, I have the following interface: export interface Defined { 4475355962119: number[]; 4475355962674: number[]; } I am trying to create objects based on this interface Defined: let defined = new Defined(); defined['447 ...

What is the process of declaring a method within a subclass and then retrieving it from a method within the parent class using Typescript?

I am currently working with this TypeScript code snippet: abstract class Base { static actions:Record<string,unknown> static getActions () { return this.actions } } class Sub extends Base { static actions = { bar:(bar:string ...