1

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'.

  • What means `leave the application`? You can't block user from closing page unless using standard `confirm` dialog – Sergey Mell May 08 '19 at 13:03
  • I don't want to block user from closing page. I just want to offer him a confirmation dialog (using CanDeactivate guard or something else) when he want to close page . – Kontar Maryna May 08 '19 at 13:54
  • I want the user freely navigate the application components, but at the moment when he closes the application, he will be offered a confirmation. – Kontar Maryna May 08 '19 at 14:00
  • I think your question is if there's a place to don't put `canDeactivate` on every route, the answer is: No, but you can put it on you main component, so it's the same as your entire application – Gaspar May 13 '19 at 19:14
  • Thank you for answer. That's exactly what i did. The only problem is that when the user leaves the main page (index.html), the warning does not show, since it is higher than the main component. – Kontar Maryna May 17 '19 at 11:58

1 Answers1

1

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;
Sergey Mell
  • 7,780
  • 1
  • 26
  • 50