如何使用指令长按Ionic2

时间:2018-06-04 15:57:55

标签: angular ionic-framework ionic2 angular-directive

我刚刚开始使用angular进行编程,如果问题很简单或者问得很严重,我会道歉。

我有自定义指令 LongPressDirective.ts

import { Directive, ElementRef, OnInit, OnDestroy ,Output , EventEmitter } 
from '@angular/core';
import { Gesture } from "ionic-angular/gestures/gesture";
declare let Hammer: any


@Directive({
 selector: '[long-press]' // Attribute selector

})
export class LongPressDirective implements OnInit, OnDestroy{
el: HTMLElement;
  pressGesture: Gesture;
@Output('long-press') onPressRelease: EventEmitter<any> = new 
EventEmitter();
//Hammer: any

 constructor(el: ElementRef) {
this.el = el.nativeElement;
console.log('Hello LongPressDirective Directive'); 
}

ngOnInit() {
//this.pressGesture = new Gesture(this.el);
this.pressGesture = new Gesture(this.el, {
recognizers: [
  [Hammer.Press, {time: 1000}]

]
 });
this.pressGesture.listen();

this.pressGesture.on('press', (event) => {
  console.log('pressed!!');
  this.onPressRelease.emit('released');
});


}

ngOnDestroy() {
this.pressGesture.destroy();
}
}

我在app.module.ts中导入了这个指令

我的HTML中的

在相同模式下使用它:

<div #detailB *ngIf = "condition" class = "imgDetailBlur" [ngStyle]=" 
{'background-image': 'url('path')'}" id="detailB" (long-press)="clearImage()" >

但非长按工作 我试图在app.module.ts和单个模块中导入che指令,但不能正常工作

1 个答案:

答案 0 :(得分:1)

我在这种模式下解决了:

创建一个新模块SharedModule.ts

import { NgModule } from '@angular/core';
import { LongPressDirective } from '../directives/long-press/long-press';

@NgModule({
   declarations: [
   LongPressDirective
  ],
exports: [
   LongPressDirective
  ]
})
export class SharedModule {

 }

在这个模块中,我声明并导入了我的自定义指令“LongPressDirective”

现在在其他模块中使用SharedModule并正常工作!