【问题标题】:How to access a class variable inside a HostListener event handler如何访问 HostListener 事件处理程序中的类变量
【发布时间】: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


【解决方案1】:

使用

@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
}

如果您强制添加,请务必强制删除。

【讨论】:

  • 那么使用渲染器而不是直接绑定的目的是什么?
  • @Chrillewoodz,如果您需要更复杂的绑定逻辑,请使用 Renderer。对于您的特定场景,HostListener 很好。
猜你喜欢
  • 1970-01-01
  • 2011-03-05
  • 2023-04-02
  • 2014-07-18
  • 2013-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多