Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical swipe/drag gesture in ionic 2

I need to use the swipeup/swipedown gestures in an Ionic 2 application. When I do

<div (swipe)='someFunction($event)'></div>

Then my someFunction(e) is being called, but only on horizontal slides -- therefore I'm unable to listen to swipes in up and down directions. (swipeup) and (swipedown) seem not to do anything at all. Do you have any idea whether this is possible at all with the Ionic beta?

like image 988
Michał Siwek Avatar asked Mar 14 '16 14:03

Michał Siwek


2 Answers

Ionic 2 makes use hammerjs library to handle its gestures.

They’ve also built their own Gesture class that effectively acts as a wrapper to hammerjs: Gesture.ts.

So you can do your own directive like:

import {Directive, ElementRef, Input, OnInit, OnDestroy} from 'angular2/core'
import {Gesture} from 'ionic-angular/gestures/gesture'
declare var Hammer: any

/*
  Class for the SwipeVertical directive (attribute (swipe) is only horizontal).

  In order to use it you must add swipe-vertical attribute to the component.
  The directives for binding functions are [swipeUp] and [swipeDown].

  IMPORTANT:
  [swipeUp] and [swipeDown] MUST be added in a component which
  already has "swipe-vertical".
*/

@Directive({
  selector: '[swipe-vertical]' // Attribute selector
})
export class SwipeVertical implements OnInit, OnDestroy {
  @Input('swipeUp') actionUp: any;
  @Input('swipeDown') actionDown: any;

  private el: HTMLElement
  private swipeGesture: Gesture
  private swipeDownGesture: Gesture

  constructor(el: ElementRef) {
    this.el = el.nativeElement
  }

  ngOnInit() {
    this.swipeGesture = new Gesture(this.el, {
      recognizers: [
          [Hammer.Swipe, {direction: Hammer.DIRECTION_VERTICAL}]
      ]
    });
    this.swipeGesture.listen()
    this.swipeGesture.on('swipeup', e => {
        this.actionUp()
    })
    this.swipeGesture.on('swipedown', e => {
        this.actionDown()
    })
  }

  ngOnDestroy() {
    this.swipeGesture.destroy()
  }
}

This code allows you to do something like this:

<div swipe-vertical [swipeUp]="mySwipeUpAction()" [swipeDown]="mySwipeDownAction()">
like image 120
Zineb Errahmouni Avatar answered Nov 20 '22 20:11

Zineb Errahmouni


Just an update, Ionic now has gesture controls. see

http://ionicframework.com/docs/v2/components/#gestures

gestures return an $event object. You can probably use this data to check whether if it's a swipeup/swipedown event.

See $event screenshot (since I can't attach images yet ;) )

like image 36
Karl Patrick Espiritu Avatar answered Nov 20 '22 19:11

Karl Patrick Espiritu