Reputation: 704
In my app component I'm checking if there are any open modals while the route is changing. In that case, I want to
I've succeeded in closing the modals if there is one open, but I cannot find a way to use something like 'event.preventDefault()'
export class AppComponent implements OnInit, OnDestroy {
private routerEventSubscription : Subscription;
constructor (
private router: Router,
private modalService: NgbModal
) { }
ngOnInit(): void {
this.routerEventSubscription = this.router.events.pipe(
filter( event => event instanceof NavigationStart ),
pairwise()
).subscribe( event => {
console.log(event);
if (this.modalService.hasOpenModals()) {
this.modalService.dismissAll();
/*** ==> Here I want to prevent the route from changing <== ***/
}
})
}
ngOnDestroy () {
this.routerEventSubscription.unsubscribe();
}
}
Upvotes: 1
Views: 2203
Reputation: 1092
The router events will not help you in preventing the navigation as they are simply a mean to let you know what is happening, for preventing the user to leave the current route they're in you need to use the canDeactivate
property of routes.
You can check the official documentation here: https://angular.io/api/router/CanDeactivate
And you can find examples/explanations online like this one: https://www.concretepage.com/angular-2/angular-candeactivate-guard-example
Basically you create a guard which implements the CanDeactivate
interface and assign that guard to all the routes in your application which you want to user to leave and implement the logic you need in the guard itself (you get the current component and can use that to implement your logic, or you can even ignore it and use some shared service or anything you want).
Upvotes: 1