Angular 如何访问HostListener事件处理程序中的类变量

Angular 如何访问HostListener事件处理程序中的类变量,angular,Angular,我试图通过检查窗口中的“ontouchstart”来检查要设置哪个事件侦听器touchend':'单击',然后我想将其添加到@HostListener中,但我无法执行此操作,因为此在文档:单击部分中不可用 你能做到这一点吗 constructor(private _globals: GlobalVariablesService, private _elementRef: ElementRef) { this.ns = _globals.ns; this.deviceListener =

我试图通过检查窗口中的“ontouchstart”来检查要设置哪个事件侦听器touchend':'单击',然后我想将其添加到
@HostListener
中,但我无法执行此操作,因为
文档:单击
部分中不可用

你能做到这一点吗

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();
  }
}
使用

@HostListener('document:'+('ontouchstart'在窗口中?'touchend':'click'),…)
或者将其强制添加到构造函数中,如此问题所示:

构造函数(elementRef:elementRef,renderer:renderer){
如果('ontouchstart'在窗口中){
this.listenFn=renderer.listenGlobal('document','ontouchstart',(event)=>{
//用“事件”做点什么
});
}否则{
this.listenFn=renderer.listenGlobal('document','click',(event)=>{
//用“事件”做点什么
});
}
}
恩贡德斯特罗(){
this.listenFn();//删除侦听器
}

如果强制添加,请确保强制删除。

查看这是否有帮助:。基本上,必须将其添加到构造函数中。@MarkRajcok在回答了我昨天发布的一个问题后,我觉得不应该像那样添加事件侦听器。您尝试访问哪个类变量?访问
deviceListener
有什么问题
this.deviceListener
应该只在
onOutsideClick(){…}
@GünterZöchbauer中工作,我可以毫无问题地访问onOutsideClick中的变量,但我不是在那里告诉angular要侦听哪些事件。这是在
@HostListener('document:click',['$event'])
部分中完成的,而不是编写
document:click
,我想编写
this.deviceListener
。我想我现在明白了。我想这对
@HostListener()
不起作用,如果需要,可以使用@MarkRajcok链接的答案中的
渲染器。使用渲染器而不是直接绑定的目的是什么?@Chrillewoodz,如果需要更复杂的绑定逻辑,可以使用渲染器。对于您的特定场景,HostListener很好。