Quick guide about how lock an Angular page both in the Angular route and the browser refresh. Reference: https://stackoverflow.com/a/55470623/7387126
import { Observable } from "rxjs";
import { HostListener } from "@angular/core";
// see https://scotch.io/courses/routing-angular-2-applications/candeactivate
// implementing this interface with a component in angular you can implement a candeactivate
// guard that automatically checks if there is the canDeactivate function and
// it allows to navigate out of the route or not
export default interface LockableComponent {
allowRedirect: boolean;
canDeactivate(): boolean;
}
canDeactivate(
component: LockableComponent,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
if (
(component.allowRedirect === false ||
(component.canDeactivate && !component.canDeactivate()))
) {
// Angular bug! The stack navigation with candeactivate guard
// messes up all the navigation stack...
// see here: https://github.com/angular/angular/issues/13586#issuecomment-402250031
this.location.go(currentState.url);
if (
window.confirm("Sure man?")
) {
return true;
} else {
return false;
}
} else {
return true;
}
}
// ... component extends LockableComponent
allowRedirect: boolean;
canDeactivate(): boolean {
return this.allowRedirect;
}
@HostListener('window:beforeunload', ['$event'])
beforeUnloadHander() {
// or directly false
this.allowRedirect;
}
const myRoutes: Routes = [
{
path: "locked-route-path",
component: ComponentThatImplementsLockedInterface,
canDeactivate: [TheCanDeactivateGuardJustMade]
}
//...
]