离子指令不发射事件
Ionic Directive not emitting event
我已经为长按创建了一个 Ionic 5 指令。以下是代码。
export class LongPressDirective implements AfterViewInit {
private delay = 800;
@Output() press = new EventEmitter();
action: any;
private longPressActive = false;
constructor(private el: ElementRef,
private gestureCtrl: GestureController,
private zone: NgZone) { }
ngAfterViewInit() {
this.loadLongPressOnElement();
}
loadLongPressOnElement() {
const gesture = this.gestureCtrl.create({
el: this.el.nativeElement,
threshold: 0,
gestureName: 'long-press',
onStart: ev => {
this.longPressActive = true;
this.longPressAction();
},
onEnd: ev => {
this.longPressActive = false;
}
});
gesture.enable(true);
}
private longPressAction() {
if (this.action) {
clearInterval(this.action);
}
this.action = setTimeout(() => {
this.zone.run(() => {
if (this.longPressActive === true) {
this.longPressActive = false;
this.press.emit();
}
});
}, this.delay);
}
}
当我在按钮中使用它并为 Popover 传递事件时,该事件始终未定义。所以,我的弹出页面出现在屏幕中间而不是按钮位置。
<ion-button appLongPress (press)="onPress($event)">
Test
</ion-button>
async onPress(ev: any) {
// ev is undefined here
// raise popover here
}
我想我需要在指令的 this.press.emit();
方法中传递事件,但我不知道传递什么。我尝试了几件事但没有成功。
在这里传递事件
onStart: ev => {
this.longPressActive = true;
this.longPressAction(ev);
},
这里
private longPressAction(ev) {
...
this.press.emit(ev);
...
}
我已经为长按创建了一个 Ionic 5 指令。以下是代码。
export class LongPressDirective implements AfterViewInit {
private delay = 800;
@Output() press = new EventEmitter();
action: any;
private longPressActive = false;
constructor(private el: ElementRef,
private gestureCtrl: GestureController,
private zone: NgZone) { }
ngAfterViewInit() {
this.loadLongPressOnElement();
}
loadLongPressOnElement() {
const gesture = this.gestureCtrl.create({
el: this.el.nativeElement,
threshold: 0,
gestureName: 'long-press',
onStart: ev => {
this.longPressActive = true;
this.longPressAction();
},
onEnd: ev => {
this.longPressActive = false;
}
});
gesture.enable(true);
}
private longPressAction() {
if (this.action) {
clearInterval(this.action);
}
this.action = setTimeout(() => {
this.zone.run(() => {
if (this.longPressActive === true) {
this.longPressActive = false;
this.press.emit();
}
});
}, this.delay);
}
}
当我在按钮中使用它并为 Popover 传递事件时,该事件始终未定义。所以,我的弹出页面出现在屏幕中间而不是按钮位置。
<ion-button appLongPress (press)="onPress($event)">
Test
</ion-button>
async onPress(ev: any) {
// ev is undefined here
// raise popover here
}
我想我需要在指令的 this.press.emit();
方法中传递事件,但我不知道传递什么。我尝试了几件事但没有成功。
在这里传递事件
onStart: ev => {
this.longPressActive = true;
this.longPressAction(ev);
},
这里
private longPressAction(ev) {
...
this.press.emit(ev);
...
}