Can I wrap two different host listeners in a single function in angular 2

201 Views Asked by At

I need to wrap 2 different host listeners in a single function so that i can call that function whenever i need listeners.

@HostListener('window:unload', ['$event'])
unloadHandler() {
  this.eventService.send({ name: 'onUnload' });
}

@HostListener('window:beforeunload', ['$event'])
beforeUnloadHander (event: Event){

  let confirmation = {
    message: undefined
  };
  this.eventService.send({ name: 'onBeforeUnload',data:confirmation });

}

Now I need to wrap it in a single function like below and can call this function whenever I need

public enable(): any {
@HostListener('window:unload', ['$event'])
unloadHandler() {
  this.eventService.send({ name: 'onUnload' });
}

@HostListener('window:beforeunload', ['$event'])
beforeUnloadHander (event: Event){

  let confirmation = {
    message: undefined
  };
  this.eventService.send({ name: 'onBeforeUnload',data:confirmation });

}
}

1

There are 1 best solutions below

0
DaumannM On

this question was already answered. You can set more then 1 Hostlistener to one function, Can I use multiple @hostlistener or events based on browser?

But what u r trying to do is not working. You dont call functions yourself that have Hostlistener on them. Those functions are automaticly triggert when the Host detects those events. So in your case, right before the tab/browser closes the unload() Functions are called.