1

Using Angular 2 how do you update the URL Path without redirecting the page.

I know you can access the params using ActivatedRoute queryParamMap Observable but what if I want to change these values and have those display in the URL.

Updating the values in the URL allows for easy bookmark-ability.

I don't want to redirect as the query params I am adding are simple data filter I want to store.

robinsio
  • 93
  • 6
  • Could you give us an example of your code please? – Pterrat Feb 14 '18 at 12:39
  • 1
    You can redirect with the router, if it's on the same component, it will only change the URL, and not the content of the page. Is it what you want, or do you want to reload the page too ? –  Feb 14 '18 at 12:42
  • How do I redirect? I do not want to reload. Sorry I don't have any sharable code yet as I am wanting to know upfront how this will work. – robinsio Feb 14 '18 at 12:44
  • You should take a look at this: https://stackoverflow.com/questions/35618463/change-route-params-without-reloading-in-angular-2 It might work for you too! – Vincent Gagnon Feb 14 '18 at 12:50

2 Answers2

1

In the component constructor subscribe the query parameter to your model.

this.route.queryParams.subscribe(params => {
  this.myValue = params['myValue'];
});

Now, register a listener function to the view model, or alternatively add a watch to your model. Then have a navigate function you can call once your model is updated:

navigate() {
    this.router.navigate([], {queryParams: { mValue: this.myValue }});
}
  • Is there a way to add params to queryParams without removing the previous ones? In the example it is basically a "=" sign, but I need it to be "+=". I want to add new value, but keep all previous ones. – Kris Bonev Jun 01 '18 at 16:30
0

Just have the same component for two different routes

const appRoutes: Routes = [
    { path: 'somepath', component: someComponent }, // yourapp/somepath
    { path: 'anotherpath', component: someComponent }, // yourapp/anotherpath
];
<a class="nav-link" routerLink="/anotherpath" routerLinkActive="active"> change path</a>
charsi
  • 2,917
  • 22
  • 40