Search code examples
angularangular-route-guards

ngOnDestroy warn user before exiting


I am trying to find a way to alert user before exiting the screen. If they press "no" then it should not destroy. And if they press "ok" then carry on with destroy operations.

Does ngOnDestory has a event that happens before ngOnDestory? for example ngOnBeforeDestroying?

I am currently developing with Angular 4.


Solution

  • yes, you should be using canDeactivate route guard.

    Create a injectable service

    @Injectable()
    class CanDeactivateService implements CanDeactivate<TeamComponent> {
    
    
      canDeactivate(
        component: TeamComponent,
        currentRoute: ActivatedRouteSnapshot,
        currentState: RouterStateSnapshot,
        nextState: RouterStateSnapshot
      ): Observable<boolean>|Promise<boolean>|boolean {
        return component.isDirty ;
     }
    }
    

    This can be used to determine if the page can be destroyed or not.

    This should be configured in Routes as

    RouterModule.forRoot([
          {
            path: '..', // path
            component: Comp, // name of the component
            canDeactivate: [CanDeactivateService]
          }
        ])
      ],
    

    Read more here...

    Angular's Official Demo

    This can be achieved through dynamic component loading also. Follow steps here