Window: popstate event
| Bubbles | No |
|---|---|
| Cancelable | No |
| Interface | PopStateEvent |
| Event handler property | onpopstate |
This event captures browser back or forward button action
Angular capture this browser back button event, and set redirect to different url:
Try this one. Import HostListener
import { Component, HostListener } from '@angular/core';
And then bind event
@HostListener('window:popstate', ['$event'])
onBrowserBackBtnClose(event: Event) {
console.log('back button pressed');
event.preventDefault();
this.router.navigate(['/home'], {replaceUrl:true});
}
https://stackoverflow.com/questions/58185653/change-route-using-browser-back-button-in-angular-6
If want to reload compnent of this redirected new URL :@HostListener('window:popstate', ['$event'])
onBrowserBackBtnClose(event: Event) {
console.log('back button pressed');
event.preventDefault();
this.router.navigate(['/home'], {replaceUrl:true});
setTimeout(
() => {
location.reload();
}
)
}
Second way:
constructor(router: Router) {
router.events
.subscribe((event: NavigationStart) => {
if (event.navigationTrigger === 'popstate') {
// Perform actions
}
});
}
https://stackoverflow.com/questions/39132737/angular-2-how-to-detect-back-button-press-using-router-and-location-go
No comments:
Post a Comment