Home > Software engineering >  Disable HostListener beforeunload on Angular 2
Disable HostListener beforeunload on Angular 2

Time:09-17

I have a canDeactivate method that alert user to save changes before leave the page:

@HostListener('window:beforeunload')
canDeactivate(): Observable<boolean> | boolean {
    return !hasChangesOnMyList();
}

I want to remove this alert when user do a specific task. I tried something like this:

window.addEventListener("beforeunload", (event) => {
   event.stopImmediatePropagation();
}, true);

But this is not working. I also tried this, without success.

window.removeEventListener('beforeunload', this.canDeactivate, true);

How can I do that?

CodePudding user response:

I haven't seen any official way to remove the listener associated with the @HostListener directive, but there are ways to achieve the same effect.

You could include a flag in your handler and set it when you no longer care about the result of !hasChangesOnMylist():

allowUnload: boolean = false;

@HostListener('window:beforeunload')
canDeactivate(): Observable<boolean> | boolean {
    return this.allowUnload || !hasChangesOnMyList();
}

someAction(): void {
    // After this, the canDeactivate() handler will
    // no longer check hasChangesOnMyList().
    this.allowUnload = true;
}

Or you could try removing the logic in the handler:

@HostListener('window:beforeunload')
canDeactivate(): Observable<boolean> | boolean {
    return !hasChangesOnMyList();
}

someAction(): void {
    // After this, the canDeactivate() handler will
    // no longer check hasChangesOnMyList().
    this.canDeactivate = function(): Observable<boolean> | boolean { return true; };
}

Either way, the handler should be cleaned up for you when the component's ngOnDestroy lifecycle hook is triggered.

  • Related