Chrillewoodz
Chrillewoodz

Reputation: 28338

How to access a class variable inside a HostListener event handler

I'm trying to check which event listener to set by checking 'ontouchstart' in window ? 'touchend' : 'click', and then I want to add this inside a @HostListener but I'm unable to do this because this is not available in the document:click section.

Can you achieve this somehow?

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

Upvotes: 1

Views: 2341

Answers (1)

Mark Rajcok
Mark Rajcok

Reputation: 364707

Use

@HostListener('document:' + ('ontouchstart' in window ? 'touchend' : 'click'), ...)

or add it imperatively inside your constructor, as shown in this question: 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
}

If you add it imperatively, be sure to remove it imperatively.

Upvotes: 3

Related Questions