找到了解决方法:
TouchEvents 实际上在 DOM 移除后会继续触发,但它们只针对原始touchstart
发生的节点/元素并且不会冒泡(与 MouseEvents 不同,这是令人困惑的!)。
因此,我们不能执行一个简单的@HostListener('touchmove', ['$event'])
操作并期望它与 DOM 删除一起工作(因为事件侦听器附加到外部组件元素)。我们必须在touchstart事件发生时动态地将事件侦听器添加到目标元素。然后对or (or )执行清理。touchend
touchcancel
ngOnDestroy()
索尔恩:
@HostListener('touchstart', ['$event'])
@HostListener('mousedown', ['$event'])
dragStart(event) {
if (event.touches) { // avoid touch event loss issue
this.removePreviousTouchListeners(); // avoid mem leaks
this.touchmoveListenFunc = this.renderer.listen(event.target, 'touchmove', (e) => { this.onDragMove(e); });
this.touchendListenFunc = this.renderer.listen(event.target, 'touchend', (e) => { this.removePreviousTouchListeners(); this.onDragEnd(e); });
this.touchcancelListenFunc = this.renderer.listen(event.target, 'touchcancel', (e) => { this.removePreviousTouchListeners(); this.onDragEnd(e); });
}
...
}
removePreviousTouchListeners() {
if (this.touchmoveListenFunc !== null)
this.touchmoveListenFunc(); // remove previous listener
if (this.touchendListenFunc !== null)
this.touchendListenFunc(); // remove previous listener
if (this.touchcancelListenFunc !== null)
this.touchcancelListenFunc(); // remove previous listener
this.touchmoveListenFunc = null;
this.touchendListenFunc = null;
this.touchcancelListenFunc = null;
}
@HostListener('mousemove', ['$event'])
// @HostListener('touchmove', ['$event']) // don't declare this, as it is added dynamically
onDragMove(event) {
... // do stuff with event
}
@HostListener('mouseup', ['$event'])
// @HostListener('touchend', ['$event']) // don't use these as they are added dynamically
// @HostListener('touchcancel', ['$event']) // don't use these as they are added dynamically
onDragEnd(event) {
... // do stuff
}
ngOnDestroy() {
this.removePreviousTouchListeners();
不要忘记Renderer
在构造函数中注入(从@angular/core
来源https://plus.google.com/+RickByers/posts/GHwpqnAFATf