Search code examples
angularangular9

How to handle long press with ngx-long-press in angular9?


I've got an issue with making longPress work in angular 9. I've imported the module following https://github.com/Gbuomprisco/ngx-long-press and I've got a simple button

<button [longPress] (onRelease)="onLongPress()" > </button>

and a simple

onLongPress(){
    console.log("long press works");
  }

in my ts file. However the console log never shows up. There is no error in the console, just nothing happens, so my question is: should this module be working with Angular 9? And if not, what is the best module to handle long press in angular 9?


Solution

  • add longPress directive

    import { Directive, ElementRef, EventEmitter, OnDestroy, OnInit, 
    
    Output } from '@angular/core';
    import { Clipboard } from '@ionic-native/clipboard';
    import { Gesture } from 'ionic-angular/gestures/gesture';
    import { Platform } from 'ionic-angular';
    declare var Hammer;
    
    @Directive({
      selector: '[longPress]'
    })
    
    export class PressDirective implements OnInit, OnDestroy {
      @Output() onLongPressEvent = new EventEmitter();
      el: HTMLElement;
      pressGesture: Gesture;
    
      constructor(el: ElementRef, private clipboard: Clipboard, private plt: Platform) {
        this.el = el.nativeElement;
        this.onLongPressEvent.emit();
      }
    
      ngOnInit() {
        if (this.plt.is('ios')) {
          this.pressGesture = new Gesture(this.el);
        } else {
          this.pressGesture = new Gesture(this.el,
            {
              recognizers: [
                [Hammer.Press, { time: 1000 }]
              ]
            });
        }
        this.pressGesture.listen();
        this.pressGesture.on('press', e => {
          this.clipboard.copy(e.target.textContent.trim());
          this.onLongPressEvent.emit();
        });
      }
    
      ngOnDestroy() {
        this.pressGesture.destroy();
      }
    }