我正在尝试通过检查'ontouchstart' in window ? 'touchend' : 'click'
来检查要设置的事件监听器,然后我想在@HostListener
内添加它,但我无法执行此操作,因为this
在document:click
部分中不可用。
你能以某种方式实现这个目标吗?
constructor(private _globals: GlobalVariablesService, private _elementRef: ElementRef) {
this.ns = _globals.ns;
this.deviceListener = ('ontouchstart' in window ? 'touchend' : 'click');
}
// How can I add the this.deviceListener instead of click?
@HostListener('document:click', ['$event'])
onOutsideClick(e) {
// If the clicked element is not the component element or any of its children, close the dropdown
if (this._elementRef.nativeElement !== e.target && !this._elementRef.nativeElement.contains(e.target)) {
this.close();
}
}
答案 0 :(得分:3)
使用
@HostListener('document:' + ('ontouchstart' in window ? 'touchend' : 'click'), ...)
或在构造函数中强制添加它,如此问题所示:Dynamically add event listener in Angular 2:
constructor(elementRef: ElementRef, renderer: Renderer) {
if('ontouchstart' in window) {
this.listenFn = renderer.listenGlobal('document', 'ontouchstart', (event) => {
// do something with 'event'
});
} else {
this.listenFn = renderer.listenGlobal('document', 'click', (event) => {
// do something with 'event'
});
}
}
ngOnDestroy() {
this.listenFn(); // removes the listener
}
如果你必须添加它,请务必将其删除。