Reputation: 16206
I have a component that should be destroyed each time the changes (for example, each time the user click to go back on history), but before the destruction of the component, I want to show a message asking if the user wants to leave without saving the changes.
The user can select the "no" answer, which the app should stop the navigation in this case. If the user selects the "yes" answer, the navigation should continue.
My question is, how can I do that?
Follows an example:
export class ListConfigurationsComponent implements OnInit, OnDestroy {
...
constructor(
...
private router: Router) {
router.events.subscribe((val) => {
//Cancel the option here
});
}
}
Upvotes: 3
Views: 8247
Reputation: 9380
A better approach would be to check for the navigationTrigger
property on the NavigationEvent
and check the previous state ID in the restoredState
property as
if(event instanceof NavigationStart && event.navigationTrigger == "popstate" && event.restoredState)
Stackblitz at https://stackblitz.com/edit/angular-check-navigation-back-fron-through-browser
Upvotes: 0
Reputation: 21367
try this using restoredState property, it's defined when the navigation is triggered by a popstate event otherwise it's null, check this
router.events.pipe(
filter(( event: NavigationEvent ) => {
return( event instanceof NavigationStart );
})
).subscribe((event: NavigationStart) => {
if (event.restoredState ) {
// display you confirmation modal
}
})
Upvotes: 4
Reputation: 301
One version could be that you don't use the [routerLink] in your template. Use the (click) handler instead to call your function which checks if the user should be redirected.
In your html
(click) = "checkDialog()";
If so in your ts just use
this.router.navigate(['/next-page']);
in your condition
Upvotes: 0
Reputation: 1187
You're looking for CanDeactivate Guard. Check this article, it describes how to make generic CanDeactivate strategy: https://medium.com/@tobias.ljungstrom/how-to-use-a-custom-dialogue-with-the-candeactivate-route-guard-in-angular-385616470b6a
Upvotes: 1