【发布时间】:2016-09-22 03:06:49
【问题描述】:
我正在尝试通过检查 'ontouchstart' in window ? 'touchend' : 'click' 来检查要设置的事件侦听器,然后我想将其添加到 @HostListener 中,但我无法这样做,因为 this 在 @ 中不可用987654325@部分。
你能以某种方式做到这一点吗?
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) {
const nativeElement = this._elementRef.nativeElement;
// If the clicked element is not the component element or any of its children, close the dropdown
if (nativeElement !== e.target && !nativeElement .contains(e.target)) {
this.close();
}
}
【问题讨论】:
-
看看这是否有帮助:stackoverflow.com/questions/35080387/…。基本上,在构造函数中强制添加它。
-
@MarkRajcok 在回答了我昨天发布的一个问题后,我的印象是你不应该添加这样的事件监听器。
-
您尝试访问什么类变量?访问
deviceListener有什么问题?this.deviceListener应该在onOutsideClick() { ... }中工作 -
@GünterZöchbauer 我可以毫无问题地访问 onOutsideClick 内部的变量,但这不是我告诉 Angular 要监听哪些事件的地方。这是在
@HostListener('document:click', ['$event'])部分完成的,而不是写document:click我想写this.deviceListener。是不是更清楚了? -
我想我现在明白了。我想这不适用于
@HostListener()使用Renderer就像@MarkRajcok 在上面链接的答案中一样,如果你需要的话。
标签: angular