I have a modal component in a certain route, but when the user navigates back to previous page with browser's back button. The modal stays open and the page behind it navigates back. This is no good UX...
Although it seems like a common problem, I cannot find many solid solutions for this problem in Angular. Certainly not in angular and Ng bootstrap docs...
What I want is to check on every route change if a modal is open and if it is: close the modal and prevent the route change.
In an older AngularJS app I solved it with the following code in appModule.run()
// Prevent browser-back to change page when modal is openend
// Source: https://stackoverflow.com/questions/23762323/is-there-a-way-to-automatically-close-angular-ui-bootstrap-modal-when-route-chan/23766070#23766070
$rootScope.$on('$locationChangeStart', function ($event, newUrl, oldUrl) {
var openedModal = $uibModalStack.getTop();
if (openedModal) {
if (!!$event.preventDefault) {
$event.preventDefault();
}
if (!!$event.stopPropagation) {
$event.stopPropagation();
}
$uibModalStack.dismiss(openedModal.key);
}
});
For Angular I found solutions with route guards, but with those solutions I need to add this guard to every route. So I'm looking for a more generic solution (like my angularJS solution).
Are there any Angular 9/10/11 best practices to solve this one?