Angular 7 Router - Navigate without adding to the history
Asked Answered
C

2

30

Using Angular Router, I want to navigate to another url without adding it to the browser history.

this.router.navigateByUrl(`${pathWithoutFragment}#${newFragment}`);

Can I do it with only Angular?

Cursorial answered 3/1, 2019 at 9:6 Comment(0)
G
57

Thanks to NavigationExtras you can now use replaceUrl: boolean inside navigate()

This will replace the current url, and the new URL will update in the address bar:

this.router.navigate([`/somewhere`], { replaceUrl: true });

That way when you press back it will not remember the previous page in the history.

Grandeur answered 26/9, 2019 at 6:47 Comment(0)
A
10

As @IngoBürk Mentioned in the comment you can achieve the same result without using skiplocationChange

 this.router.replaceUrl('path')

skipLocationChange

Navigates without pushing a new state into history.

this.router.navigateByUrl([`${pathWithoutFragment}#${newFragment}`], { skipLocationChange: true });

Ref:https://angular.io/api/router/NavigationExtras#skipLocationChange

Anglaangle answered 3/1, 2019 at 9:10 Comment(4)
I think replaceUrl is the correct answer here. skipLocationChange will not update the URL either, and it doesn't sound like that's what OP wants.Prizefight
I don't see what your edit has to do with my comment? I meant using replaceUrl instead of skipLocationChange. It's also an option of NavigationExtras.Prizefight
No, it replaces the state. Which means the URL will update in the address bar, but there's no new event on the stack, so clicking the back button leads to the same previous page as without that navigation. If you use skipLocationChange, you have that effect as well, but the URL won't update in the address bar.Prizefight
Your new edit is still wrong. Again, you need to use replaceUrl. Now you just edited to using no flag at all, which is a normal navigation. I'm going to stop trying to explain this now, I think it's been more than clear...Prizefight

© 2022 - 2024 — McMap. All rights reserved.