angular - 如何使用指令长按 Ionic2
问题描述
我刚刚开始使用 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 指令但不起作用
解决方案
我在这种模式下解决了:
创建一个新模块 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 并开始工作!