Angular 4 - How do I switch to a specific component when I click the back button?

I want to go to a specific path when the button backis clicked in the browser.

I tried to execute the following code snippet. But it momentarily changes the URL to the one you want, and then it goes to the previous actual URL.

constructor(location: PlatformLocation, private router: Router) {
    location.onPopState(() => {
        router.navigate(['/home']);
    });
}
+4
source share
3 answers

I found the solution differently and using JavaScript.

Suppose that I am in "/ menu" and I want to go to "/ home" when the back button is pressed. Check out the following code snippet.

ngOnInit() {
window.history.pushState( {} , 'Home', '/home' );
window.history.pushState( {} , 'Menu', '/menu' ); }

window.history ngOnInit(). -, URL (/home), , , URL (/menu).

, , .

+1

routerLink

https://angular.io/api/router/RouterLink

<a [routerLink]="['/main']">
 <b> < BACK </b>
</a>
+1

I would recommend putting the listener at the top level, for example:

  @HostListener('window:popstate', ['$event'])

and do

  router.navigate(['/home']);

inside.

0
source

Source: https://habr.com/ru/post/1683583/


All Articles