找到一个解决办法:
TouchEvents的确需要继续DOM去除但他们只管节点/元素发生在原touchstart
火后并没有泡沫(不像MouseEvents,这是混乱!)。
所以,我们不能执行一个简单的@HostListener('touchmove', ['$event'])
,并期望它与DOM删除(因为事件监听器附加到外部组件元素)。我们必须动态将事件侦听器添加到touchstart事件发生时的目标元素。然后执行清理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