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

前端 未结 7 1199
说谎
说谎 2020-12-08 14:43

My issue is, the methods used for both the events is getting triggered when I perform \"double click\"

For example, I need to perform specific functionality when spe

相关标签:
7条回答
  • 2020-12-08 15:30

    I haven't found a way to do it natively in Angular (or Javascript), but here's a generic way to get it working for all your click handlers.

    Although conceptually similar to the other answers, the other answers don't handle repeated clicking very well and don't maintain (and reset!) their flags on the right time.

    The idea here is to maintain a flag for deciding between the click handler and dblclick handler for a shared context (same element):

    1. The click handler waits for a short time to rule out double clicks
    2. The double click handler blocks single click handlers within that waiting period
    3. Because a double click means two single singles, on double click, again wait for a short period of time before switching the flag back, to make sure the second single click is also blocked

    Here's how you use it on your example:

        <a (click)="method1()" (dblclick)="method2()"></a>
    

    Inside your component:

        const clickContext = new ClickContext();
    
        class YourComponent {
           method1 = clickContext.clickHandler(() => { /* your method1  */ });
           method2 = clickContext.dblClickHandler(() => { /* your method2 */ });
        }
    

    For every context (element) where you need both a click and dblClick handler, you need to create a separate context. Luckily it is a rare requirement.

    Now, by using the magic util class I'll go into below, the clicks and doubleclicks are handled properly.

    Here's the class that does the flag monitoring and handler execution:

        export class ClickContext {
            private isSingleClick = true;
    
            clickHandler(handler: ClickHandler): ClickHandler {
                return function() {
                    const args = arguments;
                    this.isSingleClick = true;
                    setTimeout(() => {
                        this.isSingleClick && handler.apply(undefined, args);
                    }, 250);
                }
            }
    
            dblClickHandler(handler: ClickHandler): ClickHandler {
                return function() {
                    const args = arguments;
                    this.isSingleClick = false;
                    setTimeout(() => {
                        this.isSingleClick = true;
                    }, 250);
                    handler.apply(undefined, args);
                }
            }
        }
    
        type ClickHandler = (...any) => void;
    

    Notice that care is taken to make sure the original arguments are passed on to the target event handler method1 and method2.

    0 讨论(0)
提交回复
热议问题