So I want to show a confirmation popup when user tries t navigate to other page. I read about hostListner and canActivate ...But I'm not getting any idea where to start!
please help !!TIA.
So I want to show a confirmation popup when user tries t navigate to other page. I read about hostListner and canActivate ...But I'm not getting any idea where to start!
please help !!TIA.
first of all you need to create a guard for routing create 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;
}
}
create another file canExit.ts – This file is used to return the promised value.
import {Observable} from 'rxjs';
export interface CanExit {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
After you add the above files in your application configure the router file as follows
const routes: Routes = [
{
path: 'your Path name',
component: YourComponent ,
canDeactivate: [CanExitGuard],
}
];
// use this configuration in every path of your application
Your component file needs some changes include canactivate in your component
import { CanExit } from './../can-exit.guard'; //important
@Component({
// your selector and component defs
})
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;
}
}
}
hope this will help