Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change Angular2 route parameters without navigating to the route?

I have an angular2 page shows a list of items. I restrict the list initially by using the route paramters 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.

like image 951
Don Chambers Avatar asked Jun 09 '16 18:06

Don Chambers


People also ask

How do I change the URL in an Angular application without reloading the route?

You could use location.go(url) which will basically change your url, without change in route of application.

What is ActivatedRoute and ActivatedRouteSnapshot?

Since ActivatedRoute can be reused, ActivatedRouteSnapshot is an immutable object representing a particular version of ActivatedRoute . It exposes all the same properties as ActivatedRoute as plain values, while ActivatedRoute exposes them as observables.

Can we pass in multiple parameters to a route?

Passing Multiple Parameters Using Route to Controller In this example, will first define a route with multiple parameters and then we will add a controller method accepting multiple parameters. Then we will setup a link with named route having multiple parameters.


1 Answers

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);
like image 154
Daniel Oliveira Avatar answered Sep 30 '22 21:09

Daniel Oliveira