Blog>
Snippets

Touch Event Handling with HammerJS in Angular

Code example of integrating HammerJS for better touch event handling in Angular applications, delivering a smoother mobile user experience.
import * as Hammer from 'hammerjs';

export class MyHammerConfig extends HammerGestureConfig {
  overrides = <any>{
    'swipe': { direction: Hammer.DIRECTION_ALL },
  };
}

@NgModule({
  providers: [
    {
      provide: HAMMER_GESTURE_CONFIG,
      useClass: MyHammerConfig
    }
  ]
})
export class AppModule { }
This piece of code defines a custom HammerJS configuration for an Angular module. It overrides the default swipe gesture to support all directions.
import { Component } from '@angular/core';

@Component({
  selector: 'app-touch-example',
  templateUrl: './touch-example.component.html',
  styleUrls: ['./touch-example.component.css']
})
export class TouchExampleComponent {

  onSwipe(event: any): void {
    // Determine the direction of the swipe event
    switch (event.direction) {
      case Hammer.DIRECTION_LEFT:
        // Handle left swipe
        break;
      case Hammer.DIRECTION_RIGHT:
        // Handle right swipe
        break;
      // You can also handle DIRECTION_UP and DIRECTION_DOWN
    }
  }
}
Here we have an Angular component that uses the HammerJS swipe gesture integrated in the first piece of code. The 'onSwipe' method can be bound to a swipe event in the template, and it will handle different swipe directions.
<div (swipe)="onSwipe($event)">
  Swipe here
</div>
This is the Angular template that binds the swipe event to the 'onSwipe' method defined in our TouchExampleComponent. When the user swipes on the div element, the onSwipe event handler will be called.