Kontar Maryna
Kontar Maryna

Reputation: 11

How to use CanDeactivate guard when leave application (NOT component)

In my application, the user can be tested, see the test results. And this is all without registration (such as login-password). But if he wants to leave the application, I want to offer him to register, otherwise his data will not be saved. I do not want to offer to register when leaving a certain component, only if he wants to leave the application. I am new to angular. Perhaps for this problem there is another solution in angular, not related to CanDeactivate guard.

UPDATE:

thanks to Sergey Mell, for the angular did as follows:

export abstract class DeactivationGuarded {
 abstract canDeactivate(): Observable<boolean> | Promise<boolean> | boolean;
 @HostListener('window:beforeunload', ['$event'])
 unloadNotification($event: any) {
  if (!this.canDeactivate()) {
   $event.returnValue = true;
  }
 }
}

And then extends root component from DeactivationGuarded.

But it does not work for 'onpagehide'.

Upvotes: 1

Views: 1277

Answers (1)

Sergey Mell
Sergey Mell

Reputation: 8040

It seems like your solution should look smth like this

function myConfirmation() {
    if (user.isRegistered) {
       return;
    }
    // Open your fancy registration dialog here;
    return 'Please, register. Otherwise your data will not be saved';
}

window.onbeforeunload = myConfirmation;

Upvotes: 1

Related Questions