How to prevent double click on button in angular

To prevent double clicking on a button in Angular, you can use a combination of Angular directives and event handling.

One approach is to disable the button after it is clicked and re-enable it after a certain timeout. Here’s an example:


    <button (click)="onClick()" [disabled]="isButtonDisabled">Click me</button>
  

    import { Component, OnInit } from '@angular/core';
  
    @Component({
      selector: 'app-button',
      templateUrl: './button.component.html',
      styleUrls: ['./button.component.css']
    })
    export class ButtonComponent implements OnInit {
      isButtonDisabled = false;
  
      onClick() {
        this.isButtonDisabled = true;
        // Perform your button click logic here
        
        setTimeout(() => {
          this.isButtonDisabled = false;
        }, 3000); // Re-enable the button after 3 seconds
      }
  
      ngOnInit() {
      }
    }
  

In this example, we have a button that calls the onClick() method when clicked. The [disabled] attribute is bound to the isButtonDisabled property, which determines whether the button is disabled or not. Initially, the button is not disabled. When the button is clicked, we set isButtonDisabled to true, disable the button, and perform our button click logic. After a timeout of 3 seconds (adjust according to your needs), we set isButtonDisabled back to false, re-enabling the button.

Another approach is to use the RxJS debounceTime operator to prevent multiple button clicks within a short period of time. Here’s an example:


    import { Component, OnInit } from '@angular/core';
    import { Subject } from 'rxjs';
    import { debounceTime } from 'rxjs/operators';
  
    @Component({
      selector: 'app-button',
      templateUrl: './button.component.html',
      styleUrls: ['./button.component.css']
    })
    export class ButtonComponent implements OnInit {
      private clickSubject = new Subject();
  
      onClick() {
        this.clickSubject.next();
      }
  
      ngOnInit() {
        this.clickSubject.pipe(
          debounceTime(1000) // Wait for 1 second before emitting next value
        ).subscribe(() => {
          // Perform your button click logic here
        });
      }
    }
  

In this example, we have a clickSubject that acts as a source for button clicks. When the button is clicked, we call the next() method on clickSubject. The clickSubject is then piped through debounceTime(1000), which delays the emission of values for 1 second. This means that if the button is clicked multiple times within 1 second, only the last click will be processed. You can adjust the debounceTime according to your needs.

Leave a comment