In my application I want to show a prompt message box or a modal whenever the user hits back button. I am able to use onPopState event but it doesn't prevent the user from navigating backwards. So far, I have this:
window.onpopstate = (event) =>
event.preventDefault();
this.modal.showModal();
};
Here's how i do it in my app.
Import angular's 'Location' API in your module.
Add it to the provider's list
Note - you may not need the 'PathLocatioStrategy' part of that if you're not rewriting URLs manually.
Then in your root component, or a singleton service, import Location again...
inject it into the constructor
Then subscribe to the 'back' PopStateEvent.
If you're using the Angular router or anything else that uses the Angular Location API and path-rewriting, it may prevent this from working. I don't use the Angular router much but I'm guessing it probably has a method for dealing with PopStateEvents.
Instead of using the window object, you should use a route guard. In your route configuration, you should add a CanDeactivate guard. Follow this guide, it is very similar to what you want to accomplish.
Angular 2/4 provides a way to do just the same. And the solution is canDeactivate.
canDeactivate is a route property that can be added to the route whose component contains the back button.
The canDeactivate guard takes a service as an Input. The Service implements the canDeactivate Interface(@angular/router).
If only this service returns true, the the user would be allowed to go back.
Further Reading: https://angular.io/guide/router#candeactivate-handling-unsaved-changes