25

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?

Marc
  • 12,706
  • 7
  • 61
  • 97
Alex York
  • 365
  • 1
  • 3
  • 6

2 Answers2

46

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.

Elron
  • 1,235
  • 1
  • 13
  • 26
7

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

Chellappan வ
  • 23,645
  • 3
  • 29
  • 60
  • 2
    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. – Ingo Bürk Jan 03 '19 at 09:43
  • 1
    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`. – Ingo Bürk Jan 03 '19 at 10:09
  • 3
    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. – Ingo Bürk Jan 03 '19 at 10:13
  • 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... – Ingo Bürk Jan 03 '19 at 10:23