I came across this question a bit after the fact, but I hope to help someone else come here.
The main candidate for the solution is the route security service.
See here for an explanation: https://angular.io/guide/router#candeactivate-handling-unsaved-changes
The corresponding part (almost literally copied) is the implementation:
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import { MyComponent} from './my-component/my-component.component'; @Injectable() export class CanDeactivateGuard implements CanDeactivate<MyComponent> { canDeactivate( component: MyComponent, route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<boolean> | boolean {
Where MyComponent is your custom component, and CanDeactivateGuard will be registered in your AppModule in the providers section and, more importantly, in your routing configuration in the canDeactivate array canDeactivate :
{ path: 'somePath', component: MyComponent, canDeactivate: [CanDeactivateGuard] },
A. Chiesa
source share