Angular 2: Prevent router from adding to history

13,368

Solution 1

It turns out there is a built-in way for Angular 2's routing to skip adding a state to the history. We actually found it checking through random properties inside the intellisense of the editor.

Our routing code just had to go from:

this.router.navigate([`/myPage/${this.Id}`], { relativeTo: this.route });

to:

this.router.navigate([`/myPage/${this.Id}`], { relativeTo: this.route, skipLocationChange: true });

Solution 2

In addition, there is an option in NavigationExtras, which allows to replace current state in history with new one:

this.router.navigate(['/view'], {replaceUrl: true});
Share:
13,368
My Stack Overfloweth
Author by

My Stack Overfloweth

My interest in development started with me wanting to build my own video game website at an early age followed by a desire to hack the games I was currently playing. I'm proficient in several languages but mostly work professionally in a full-stack Web and Microsoft technology environment. I also have a big interest in database administration. These days I find myself more motivated by the people I work with rather than the technologies.

Updated on June 07, 2022

Comments

  • My Stack Overfloweth
    My Stack Overfloweth almost 2 years

    We have a client that is iFraming in our app to their website. They don't want the router navigation within our app to affect the back button navigation for their own site.

    We've tried a couple methods including using post messages to try and have the iFrame communicate with the parent window whenever a history.back() is triggered.

    My question is if there is any easy way to not affect the browser's history when using Angular 2's router. As far as I know, I couldn't find anything within Angular 2's advanced router documentation: https://angular.io/docs/ts/latest/guide/router.html