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.

4
  • Could you give us an example of your code please? Commented Feb 14, 2018 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 ? Commented Feb 14, 2018 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. Commented Feb 14, 2018 at 12:44
  • You should take a look at this: stackoverflow.com/questions/35618463/… It might work for you too! Commented Feb 14, 2018 at 12:50

2 Answers 2

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 }});
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.