Configure Hammerjs events with angular2

前端 未结 4 1492
天命终不由人
天命终不由人 2020-12-14 05:25

How can I configure hammerjs events in angular2?

To use hammerjs events with angular2 I just have to include events on my html like this:

4条回答
  •  忘掉有多难
    2020-12-14 05:44

    It's not something easy since it's internally handled by the CustomHammerGesturesPlugin class. I see two approaches:

    • Provide your own Hammer plugin and register it. When the Hammer object is instantiated, you need to provide your configuration as second parameter:

      @Injectable()
      export class CustomHammerGesturesPlugin extends HammerGesturesPlugin {
        addEventListener(element: HTMLElement, eventName: string, handler: Function): Function {
          var zone = this.manager.getZone();
          eventName = eventName.toLowerCase();
      
          return zone.runOutsideAngular(function() {
            // Creating the manager bind events, must be done outside of angular
            var mc = new Hammer(element); // <-------
            mc.get('pinch').set({enable: true});
            mc.get('rotate').set({enable: true});
            var handler = function(eventObj) { zone.run(function() { handler(eventObj); }); };
            mc.on(eventName, handler);
            return () => { mc.off(eventName, handler); };
          });
        }
      }
      

      Since the HammerGesturesPlugin provider is automatically register when using the bootstrap function, you need to use this code to bootstrap your application (see https://github.com/angular/angular/blob/master/modules/angular2/platform/browser.ts#L110 and https://github.com/angular/angular/blob/master/modules/angular2/src/platform/browser_common.ts#L79):

      platform(BROWSER_PROVIDERS).application(appProviders).bootstrap(appComponentType);
      
    • A workaround could be to intercept the instantiation of the Hammer object (see Can I intercept a function called directly?):

      
      

      See this plunkr: https://plnkr.co/edit/eBBC9d?p=preview.

    Otherwise I don't know which version of Angular2 you use but there is a problem with Hammer events (beta.0 seems to be okay):

    • https://github.com/angular/angular/issues/6993

提交回复
热议问题