0

I'm trying to restrict the user to navigate to any link if there are any unsaved changes left, it works fine for most of the cases except two:

  1. When user clicked the Log Out
  2. When user clicked on a toggle button which is on layout level.

I tried to restrict the event by using Event but it is showing it as deprecated.

`

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

  canDeactivate(): Observable<boolean> | boolean {

    if(*some condition*)
    {
      if(event)
      {
        event.preventDefault();
        event.stopPropagation();
      }
    }
      return *some condition*;

  }

`

I just wanted to stop the further propagation of the request

Rajat Nigam
  • 99
  • 2
  • 5
  • Does this answer your question? [Is there any lifecycle hook like window.onbeforeunload in Angular2?](https://stackoverflow.com/questions/36763141/is-there-any-lifecycle-hook-like-window-onbeforeunload-in-angular2) – Adrian Kokot Jul 04 '23 at 08:05
  • I tried this but it still not able to solve my problem. @AdrianKokot – Rajat Nigam Jul 04 '23 at 08:27

1 Answers1

0

When you are using event, you are using the deprecated window.event variable.

You can see its documentation here (and also why it is deprecated)

Your problem is that you want to use the event passed as an argument to the canDeactivate method, this method actually don't have any parameter (even if you declared in in your HostListener)

So all you have to do is pass add the event in the parameters of the method

 canDeactivate(event: BeforeUnloadEvent): Observable<boolean> | boolean {

That way you will use the event from the method parameter, not the window object

Florent M.
  • 1,107
  • 1
  • 6
  • 14
  • I tried this way but in this scenario the event is coming as undefined. – Rajat Nigam Jul 04 '23 at 08:18
  • It works for me. https://codesandbox.io/s/angular-11-playground-forked-qftsjv?file=/src/app/app.component.ts:544-549 (open the console and try to refresh the page) – Florent M. Jul 04 '23 at 08:34
  • Yes, it worked for most of the cases like if you reload of navigate to any link but it is failing in only one case where it interacted with event like checkbox or button. Please try with checkbox. @Florent M – Rajat Nigam Jul 04 '23 at 08:37