10

I have an angular2 page shows a list of items. I restrict the list initially by using the route parameters so my URL is something like:

http://localhost:54675/#/listing?filter={"Country":[6, 7]}

This will show items in the country with an ID of 6 or 7.

Then the users adds a third country (let's say 8) and I make a service call which updates the list. Since the list items are bound to an observable the list then updates on the screen.

This is exactly the behavior I want. But if the user bookmarks this page they only get the original route parameters and not the filtered results.

To fix this, I use:

this._router.navigate(['listing', { filter: newfilter }]);

This reloads the page with this route:

http://localhost:54675/#/listing?filter={"Country":[6,7,8]}

This keeps everything in sync and bookmarks work. However, there is a full page refresh. Other items load again - not just the filtered results. I also like the visual results better when it's just a single service call.

I need a way to change the route parameters without reloading the page.

1
  • Did you ever get this working? Commented Jan 5, 2017 at 2:29

2 Answers 2

23

You can use the Router only to create the URL and then use the Location to change the URL without navigating.

Something like this:

import { Location } from '@angular/common';
import { Router } from '@angular/router';

// Generate the URL:
let url = this.router.createUrlTree(['listing', { filter: newfilter }]).toString();

// Change the URL without navigate:
this.location.go(url);
Sign up to request clarification or add additional context in comments.

1 Comment

A very elegant and clean solution! I wanted to add an ID to my route and it worked :) I used the this.location.replaceState so that when clicking to return to the previous page it would work as expected instead of going back to the same route without the ID.
4

For anyone who still didn't find a proper solution, try this:

this._router.navigate([], { 
 relativeTo: this.activatedRoute,
 queryParams: {
   filter: newfilter
 },
 queryParamsHandling: 'merge'
});

When navigating to the same route, the site doesn't reload!

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.