How to handle "single click" and "double click" on the same html DOM element using typescript:Angular 2 or 4?

You can use a timeout and a boolean flag to solve this. Consider the following:

The DOM takes a few milliseconds to recognize the double click.

But it's damn sure that it recognize the double click but the first click is also recognized.

So the logic goes like this.

isSingleClick: Boolean = true;     

method1CallForClick(){
   this.isSingleClick = true;
        settimeout(()=>{
            if(this.isSingleClick){
                 doTheStuffHere();
            }
         },250)
}
method2CallForDblClick(){
         this.isSingleClick = false;
         doTheStuffDblClickHere();
}

Call the method one in the click event of the element and method 2 in the click event of the element.


You can the pure JavaScript call back dblclick, Or as you use in angular 2 : (dblclick)="doubleClickFunction()".

If you have both (click) and (dblclick) on the same element you should add a timeout to your click event callback to avoid it been called when user double click.

Try something like:

.html:

<button (click)="singleClick()" (dblclick)="doubleClick()">click</button>

.js:

singleClick(): void{
    this.timer = 0;
    this.preventSimpleClick = false;
    let delay = 200;

    this.timer = setTimeout(() => {
      if(!this.preventSimpleClick){
        ...
      }
    }, delay);

  }

  doubleClick(): void{
    this.preventSimpleClick = true;
    clearTimeout(this.timer);
    ...
  }

clickCount = 0;
click() {
    this.clickCount++;
    setTimeout(() => {
        if (this.clickCount === 1) {
             // single
        } else if (this.clickCount === 2) {
            // double
        }
        this.clickCount = 0;
    }, 250)
}

Tags:

Angular