Implement swipe gesture in Angular application
2 min readApr 2, 2018
Abstract: Implement swipe gestures in the angular application so it will change default day and display events from the selected day. On swipe right, it will load next day and on swipe left it will load a previous day.
List of steps:
- Implement service that we will use to communicate between components
- Identify parent component
- Bind events touchstart and touchend to parent view
- Implement swipe method in a controller
- Identify component where we want to catch gestures
Here is communication service that uses BehaviorSubject.
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';@Injectable()
export class SwipeService {private messageSource = new BehaviorSubject("");currentMessage = this.messageSource.asObservable();constructor() { }setDirection(message: string) {
this.messageSource.next(message);
}public swipeNext (){
this.setDirection("next");
}public swipePrevious (){
this.setDirection("previous");
}}
We need to identify component which is suitable to bind events and to add a method that recognizes gestures (here I call it parent component):
In view of parent component set
<div class="app-container" (touchstart)="swipe($event, 'start')" (touchend)="swipe($event, 'end')">
...
</div>
Implement swipe method in parent controller
private swipeCoord?: [number, number];
private swipeTime?: number;swipe(e: TouchEvent, when: string): void {const coord: [number, number] = [e.changedTouches[0].pageX, e.changedTouches[0].pageY];
const time = new Date().getTime();if (when === 'start') {
this.swipeCoord = coord;
this.swipeTime = time;
}else if (when === 'end') {
const direction = [coord[0] - this.swipeCoord[0], coord[1] - this.swipeCoord[1]];
const duration = time - this.swipeTime;if (duration < 1000
&& Math.abs(direction[0]) > 30
&& Math.abs(direction[0]) > Math.abs(direction[1] * 3)) {
if (direction[0] < 0) {
//next
this.swipeService.swipeNext();
} else {
//previous
this.swipeService.swipePrevious();
}
}
}
}
Here we can fine tune gesture (at last if).
duration < 1000 - condition for duration in ms of swipeMath.abs(direction[0]) > 30 - condition of length if movementMath.abs(direction[0]) > Math.abs(direction[1] * 3)) - condition for horizontal movement
Now we want to find “child” component and subscribe to swipe gesture.
this.swipeSubsciption = this.swipeService.currentMessage.subscribe(message =>{
if (message === 'next'){
this.nextDay();
}
if (message === 'previous'){
this.previousDay();
}
});
Don’t forget to unsubscribe!