Search code examples
javascriptangularionic-frameworkhammer.jsionic5

Hammer.js swipe left gesture animation in Angular


I'm trying to have a swipe animation when user swipes left in the device.

Here's a gist of the problem

  • When I click on about page button in Home page, the app smoothly navigates to About page.
  • When I hit on back icon button in the top bar of About page, it gives a back swipe animation.

I've implemented Hammer.js swipe left gesture for going back but it doesn't show any animation as that of back button animation. How could I achieve that?

I created a working example using StackBlitz to better explain the problem. Could anyone please help?

about button

HTML

<ion-content (swipeleft)="goBack()">
  <h2>About page</h2>
</ion-content>

TS

export class AboutPage implements OnInit {
  constructor(private location: Location) {}

  ngOnInit() {}

  goBack() {
    this.location.back();
  }
}

Solution

  • Finally, I got this implemented using Ionic Gestures.

    Here's the working example. Swipe left to right from about page, it will result a smooth animation and takes back to the page from you where came from.

    Swipe Gesture Animation

    async ngAfterViewInit() {
        let gesture = await this.gestureCtrl.create({
          el: this.aboutPage.nativeElement,
          gestureName: 'swipe-left',
          gesturePriority: 100,
          threshold: 5,
          passive: false,
          onStart: () => {
            this.renderer.setStyle(
              this.aboutPage.nativeElement,
              'transition',
              'none'
            );
          },
          onMove: (ev) => {
            if (ev.deltaX > 0) {
              this.renderer.setStyle(
                this.aboutPage.nativeElement,
                'transform',
                `translateX(${ev.deltaX}px)`
              );
            }
          },
          onEnd: (ev) => {
            this.renderer.setStyle(
              this.aboutPage.nativeElement,
              'transition',
              '0.4s ease-out'
            );
            if (ev.deltaX > 100) {
              this.renderer.setStyle(
                this.aboutPage.nativeElement,
                'transform',
                'translateX(400px)'
              );
              this.location.back();
            }
            if (ev.deltaX < 100) {
              this.renderer.setStyle(
                this.aboutPage.nativeElement,
                'transform',
                'translateX(0px)'
              );
            }
          },
        });
        gesture.enable(true);
      }
    

    Result of the animation

    swipe-gif