If I have a form in a view (Angular). When user tries to navigate away from there, and I want a confirmation message to appear. How can I do that?
If your site needs prevent route change for multiple pages, i suppose it might be convenient to use this service:
import { Injectable } from '@angular/core';
import { CanActivateChild } from '@angular/router';
@Injectable()
export class NavPreventerService implements CanActivateChild {
locks: any = {};
constructor() {
// Bonus: If necessary also prevent closing the window:
window.addEventListener('beforeunload', (event) => {
if (this.hasRoutingLocks()) {
event.preventDefault();
event.returnValue = '';
}
});
}
canActivateChild() {
if (this.hasRoutingLocks()) {
if (confirm('Leave site?')) {
this.removeAllRoutingLocks();
return true;
}
return false;
}
return true;
}
setRoutingLock(key: string) {
this.locks[key] = true;
}
removeRoutingLock(key: string) {
delete this.locks[key];
}
removeAllRoutingLocks() {
this.locks = {};
}
hasRoutingLocks(): boolean {
return !!Object.keys(this.locks).length;
}
}
When it is necessary to prevent navigation, then in your component call
this.navPreventer.setRoutingLock('quiz-form');
Your application routing file should be like this:
export const appRoutesLocal: Routes = [
{path: '', canActivateChild: [NavPreventerService], children: [
{path: '', component: HomePageComponent},
]}
];