Getting Started with HammerJS in Angular 9

Apr 26th 2020

I couldn't find a nice all-in-one article about getting HammerJS to work with Angular 9 so I thought I would put one together.

The idea is that the Angular 9 @angular/platform-browser package comes with HammerJS event bindings prepackaged in HammerModule. However, as indicated in a footnote in the angular documentation page for the HammerModule, you still have to install hammerjs and include it in your project yourself or else the event bindings simply do nothing.

First, install HammerJS by running npm install --save hammerjs to install the hammerjs package in your project.

Then we need to properly require the hammerjs library in our app.module.ts and import the HammerModule from @angular/platform-browser:

//app.module.ts

import { NgModule, Component, InjectionToken, Inject, PLATFORM_ID} from "@angular/core";
import { BrowserModule, HammerModule } from "@angular/platform-browser";

// ... (other imports)

@NgModule({
  imports: [
    // ... (other modules)
    HammerModule
  ],
  // ... (other NgModule options)
})
export class AppModule {
  constructor(@Inject(PLATFORM_ID) private platformId: Object){
    if(isPlatformBrowser(this.platformId)){
      
      // here we require the hammerjs dependency in a block that will 
      // only run if we're actually in the browser. Otherwise the 
      // hammerjs code will cause failures in server (SSR) mode.

      require('hammerjs');
      
      // ... (other browser-only code)
    }
  } 
};

Now you can get started using touch-device gestures in your web applications such as swipe, tap, and pinch. The complete list of events cam be found on the official HammerJS documentation page.

// ...in my.component.html
<div (swipeRight)="onSwipeRight($event)">
  SWIPE RIGHT
</div>

// ...in my.component.ts
public onSwipeRight(event: Event){
  // ... react to right swipe here ...
  this.router.navigateByUrl('/my_page');
}

I hope this saves some people's time! I found a bunch of articles about transitioning HammerJS from other Angular versions, but none about getting started with HammerJS in Angular 9+.

If you were helped by this article please consider following us on twitter, facebook, youtube, or instagram.

Comments

SHOW LESS