andy brandt's blog

angular 4 hammer config

hammer is a very nice library to make detecting different types of touches very easy. from everything i read, it sounded like angular had some built in support for hammer. the problem came when i needed to configure hammer, for example, we were only interested in detecting horizontal swipes, but we still wanted to be able to scroll vertically, so it wasn’t exactly clear how to achieve that.

there are two great tutorials (one, two) available, but they didn’t go into detail on how to pass configuration to hammer, other than the fine-grained configuration on how how each recognizer behaves.

the touch-action property, which appears to be automatically calculated by default, was being set to none. i believe this is because angular appears to enable the pinch & rotate recognizers by default, which hammer then calculates the best touch-action to set is none.

as mentioned in the above tutorial, angular provides the HammerGestureConfig class, which you can extend. i then provided my own buildHammer() method which creates a new Hammer instance, without the pinch & rotate recognizers enabled. this allows hammer to properly calculate touch-action: pan-y; on the element, since i’m only using the swipeleft & swiperight recognizers.

import { HAMMER_GESTURE_CONFIG, HammerGestureConfig } from '@angular/platform-browser';

export class MyHammerConfig extends HammerGestureConfig {
    public buildHammer(element: HTMLElement): any {
        return new (window as any).Hammer(element);
    }
}

@NgModule({
    // Your module definition...
    providers: [
        {
            provide: HAMMER_GESTURE_CONFIG,
            useClass: MyHammerConfig
        }
    ]
})
export class YourModule { }

you could also provide your own config to hammer using the following as well, if hammer isn’t calculating the desired touch-action for you:

export class MyHammerConfig extends HammerGestureConfig {
    public buildHammer(element: HTMLElement): any {
        return new (window as any).Hammer(element, { touchAction: 'pan-y' });
    }
}