ngTouch (ng-swipe-left / ng-swipe-right) in modern Angular
ngTouch has no direct successor. Swipe gestures are written with native pointer events, usually wrapped in a small directive.
Before · AngularJS
<div class="slide"
ng-swipe-left="vm.next()"
ng-swipe-right="vm.prev()">
<img ng-src="{{ vm.current.url }}">
</div>After · Angular@Directive({
selector: '[appSwipe]',
host: {
'(pointerdown)': 'startX = $event.clientX',
'(pointerup)': 'end($event)',
'style': 'touch-action: pan-y',
},
})
export class SwipeDirective {
swipe = output<'left' | 'right'>();
startX = 0;
end(e: PointerEvent) {
const dx = e.clientX - this.startX;
if (Math.abs(dx) > 40) { this.swipe.emit(dx < 0 ? 'left' : 'right'); }
}
}What changes
- Pointer events cover mouse, touch and pen with one API, so there is no extra module to load.
- The touch-action CSS property tells the browser which gestures it may keep for scrolling; without it the browser can cancel the pointer sequence.
- HammerJS is no longer maintained, so avoid building new gesture code on top of it.
Migration tip. Check whether the gesture is needed at all. Many carousels that used ng-swipe can be rebuilt with CSS scroll snap, which gives native swiping without any gesture code.
Related
- $resource .$promise and $resolved
- $http cache / $cacheFactory
- jQuery / angular.element in directives
- ng-pluralize
Planning a migration or a micro-frontend platform?
In a 20-minute call you describe your situation and I tell you how I'd approach it. If it isn't worth doing yet, I'll say so.
Message me on LinkedIn