To start, you must create a guard for routing by creating a file named can-exit.guard.ts
import {Injectable} from '@angular/core';
import {CanDeactivate} from '@angular/router';
import {Observable} from 'rxjs';
export interface CanExit {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
@Injectable()
export class CanExitGuard implements CanDeactivate<CanExit> {
canDeactivate(component: CanExit) {
if (component.canDeactivate) {
return component.canDeactivate();
}
return true;
}
}
Next, create another file named canExit.ts to handle returning the promised value.
import {Observable} from 'rxjs';
export interface CanExit {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
Once you have added these files to your application, configure the router file as shown below:
const routes: Routes = [
{
path: 'your Path name',
component: YourComponent ,
canDeactivate: [CanExitGuard],
}
];
// Apply this configuration to every path in your application
Make sure to include canactivate in your component file by making some changes:
import { CanExit } from './../can-exit.guard'; //important
@Component({
// include your selector and component definitions here
})
export class YourComponent implements OnInit, CanExit {
constructor() { }
ngOnInit() {
}
canDeactivate(): Promise<any> | boolean {
const confirmResult = confirm('Are you sure you want to leave this page ? ');
if (confirmResult === true) {
return true;
} else {
return false;
}
}
}
I hope this information proves helpful.