I am using Angular 5 ad have Implemented a CanDeactivateGuard for a component to pop up a modal if there are some unsaved changes:
export interface CanComponentDeactivate {
canDeactivate: (nextStateUrl: string) => Observable<boolean> | boolean;
}
@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(
component: CanComponentDeactivate,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState?: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return component && component.canDeactivate
? component.canDeactivate(nextState.url)
: true;
}
}
I have added this guard to page2 and it works perfectly if I navigate from page 1 to page2 and make some changes and try to navigate away. However, if I stay in page2 and refresh the page and then make some changes, and try to navigate away, the canDeactivate method in the guard will be called, but the component value is null, so it returns true without showing the confirmation modal. Or if I navigate from page2 to another page which is not loaded yet. Note that all pages are lazyloaded and each page has its route module.
I have added the guard to page2 module the same way done here: http://plnkr.co/edit/z2OqgTXTiPpTgXcmNiDM?p=preview
I also tried to add the guard to main guard, but didn't work either.
Is there any reason when I refresh the component is null but when I navigate from other pages to page 2, the component is not in the guard.
Is here any fix for it?
Thanks