Search code examples
javascriptangularrxjsionic2ionic4

How to prevent multiple clicks in Ionic 4 using debouncetime?


I am trying to avoid double clicks or double taps of button in ionic 4 as it should trigger action only on single click. If I double click, I want an action to be triggered once and not 2 times. I have tried several options such as disable button, settimeout but nothing worked. While searching for better solutions, I find many forums suggested debounceTime in Angular.

I followed the answer suggested in How to prevent double click in Angular? and tried to create a directive, but clicking of "debounceClick" gives me the below error.

ERROR Error: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'debounceTime' since it isn't a known property of 'button'. ("
</ion-content>

<button appIonCLick (debounceClick)="log()" [ERROR ->][debounceTime]="700">Throttled Click</button>

The following is the directive I created

import {
  Directive, EventEmitter, HostListener, Input, OnDestroy, OnInit,
  Output
} from '@angular/core';
import { Subject } from 'rxjs';
import { Subscription } from 'rxjs';
import { debounceTime } from 'rxjs/operators';


@Directive({
  selector: '[appIonCLick]'
})
export class IonCLickDirective implements OnInit, OnDestroy {

  @Input()
  debounceTime = 500;

  @Output()
  debounceClick = new EventEmitter();

  private clicks = new Subject();
  private subscription: Subscription;

  constructor() { }

  ngOnInit() {
    this.subscription = this.clicks.pipe(
      debounceTime(this.debounceTime)
    ).subscribe(e => this.debounceClick.emit(e));
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  @HostListener('click', ['$event'])
  clickEvent(event) {
    event.preventDefault();
    event.stopPropagation();
    this.clicks.next(event);
  }
}

And below is the HTML

<button appIonCLick (debounceClick)="log()" [debounceTime]="700">Debounce Click</button> 

Can someone please help me if I am doing something wrong? I have no luck searching for debounceTime for ionic button click. Any help is appreciated!


Solution

    1. Try to import the directive 'IonCLickDirective' in the declaration section of the module where you need to use this.
    2. <button appIonCLick (debounceClick)="log()" debounceTime="700">Debounce Click</button> try this [debounceTime] -> debounceTime