在Angular2中使用移动事件

Eri*_*alo 11 dom-events hammer.js typescript angular

我想知道我是否可以获得有关移动设备事件的帮助.我正在寻找一种方法将函数绑定到Angular 2中的滑动事件.我在Github上看到这个问题,提到Angular 2使用Hammer.js进行移动事件处理.

我在使事件工作时遇到一些麻烦,因为我收到以下错误:

EXCEPTION:Hammer.js未加载,无法绑定swipeleft事件

我的代码片段如下:

import {Component, View, AfterContentInit} from 'angular2/core';
import {HelperService} from "./helper-service";
import {HammerGesturesPluginCommon} from 'angular2/src/platform/dom/events/hammer_common'

@View({
  template: `<div [id]="middleCircle" (swipeleft)="doThis()"></div>`
})

export class ColumnDirective implements AfterContentInit {
  constructor(private helperService:HelperService) {}
  doThis(){
     console.log('This thing has been done.');
   }
 }
Run Code Online (Sandbox Code Playgroud)

如果我将Hammer Gestures添加到我的构造函数中,我会收到此错误:

constructor(private helperService:HelperService, private hammerGesturesPluginCommon: HammerGesturesPluginCommon) {}
Run Code Online (Sandbox Code Playgroud)

例外:没有提供者!(ColumnDirective - > t)

任何有关此问题的帮助将不胜感激!

bra*_*ndo 13

经过大量的摆弄,我没有成功让Angular2的HammerGesturesPluginCommon工作(到目前为止).受Bill Mayes回答的启发,我提交这个作为他的答案的详细说明,我能够开始工作(在Ipad mini和Android手机上测试).

基本上,我的解决方案如下.

首先,在index.html文件的脚本标签中手动引用hammer.js(我也引用锤子时间来消除300ms延迟):

其次,安装hammerjs的类型定义(tsd install hammerjs -save).然后你可以像这样创建一个Angular2 attibute指令:

/// <reference path="./../../../typings/hammerjs/hammerjs.d.ts" />
import {Directive, ElementRef, AfterViewInit, Output, EventEmitter} from 'angular2/core';
@Directive({
    selector: '[hammer-gestures]'
})
export class HammerGesturesDirective implements AfterViewInit {
    @Output() onGesture = new EventEmitter();
    static hammerInitialized = false;
    constructor(private el: ElementRef) {

    }
    ngAfterViewInit() {

        if (!HammerGesturesDirective.hammerInitialized) {

            let hammertime = new Hammer(this.el.nativeElement);
            hammertime.get('swipe').set({ direction: Hammer.DIRECTION_ALL });
            hammertime.on("swipeup", (ev) => {
                this.onGesture.emit("swipeup");
            });
            hammertime.on("swipedown", (ev) => {
                this.onGesture.emit("swipedown");
            });
            hammertime.on("swipeleft", (ev) => {
                this.onGesture.emit("swipeleft");
            });
            hammertime.on("swiperight", (ev) => {
                this.onGesture.emit("swiperight");
            });
            hammertime.on("tap", (ev) => {
                this.onGesture.emit("tap");
            });

            HammerGesturesDirective.hammerInitialized = true;
        }


    }
}
Run Code Online (Sandbox Code Playgroud)

如果要检测垂直(向上/向下)滑动(左/右滑动是默认值,而不是垂直滑动),则需要设置Hammer.DIRECTION_ALL.关于锤子api的更多选项可以在这里找到:http://hammerjs.github.io/api/#hammer

最后,在您的父组件中,您可以执行以下操作:

import {Component} from "angular2/core";
import {HammerGesturesDirective} from "./path/HammerGesturesDirective";

    @Component({
        selector: "my-ng2-component",
        template: `<div style='width:100px; height: 100px;background-color: red' 
            (onGesture)="doSwipe($event)" hammer-gestures></div>`,
        directives: [HammerGesturesDirective]

    })
    export class MyNg2Component {
        constructor() { }

        doSwipe(direction: string) {
            alert(direction);
        }

    }
Run Code Online (Sandbox Code Playgroud)

这样,当您想要在任何特定元素上启用锤子手势时,您只需要引用属性hammer-gestures. 注意:该元素似乎需要一个唯一的ID才能工作.

  • 我还没有测试过这个,但我非常喜欢这个想法,我在办公室大声说"很酷".它看起来很干净 (2认同)

Mik*_*e M 7

那么,在OP之后很久,但是如果你只有简单的要求并且不想用hammer.js捣碎,这里是一个基本的水平狙击手.只需放入一个组件并添加自己的doSwipeLeftdoSwipeRight功能.

  touch1 = {x:0,y:0,time:0};

  @HostListener('touchstart', ['$event'])
  @HostListener('touchend', ['$event'])
  //@HostListener('touchmove', ['$event'])
  @HostListener('touchcancel', ['$event'])
  handleTouch(ev){
    var touch = ev.touches[0] || ev.changedTouches[0];
    if (ev.type === 'touchstart'){
      this.touch1.x = touch.pageX;
      this.touch1.y = touch.pageY;
      this.touch1.time = ev.timeStamp;
    } else if (ev.type === 'touchend'){
      var dx = touch.pageX - this.touch1.x;
      var dy = touch.pageY - this.touch1.y;
      var dt = ev.timeStamp - this.touch1.time;

      if (dt < 500){
        // swipe lasted less than 500 ms
        if (Math.abs(dx) > 60){
          // delta x is at least 60 pixels
          if (dx > 0){
            this.doSwipeLeft(ev);
          } else {
            this.doSwipeRight(ev);
          }
        }
      }
    } 
  }
Run Code Online (Sandbox Code Playgroud)