Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 New Router: Change / Set Query Params

I have a component registered at /contacts, which displays a list of contacts. I've added an <input [value]="searchString"> for filtering the displayed list.


Now I'd like to display the searchString within the URL in form of a Query Param. (Using the New Router 3.0.0 RC2)

The official docs ( https://angular.io/docs/ts/latest/guide/router.html#!#query-parameters ) show how to use router.navigate for changing the queryParams. But this seems awkward, because I just want to change the queryParams without having to know which route I'm currently at: router.navigate(['/contacts'], {queryParams:{foo:42}})

(I know that it doesn't reload the component if I'm just changing the queryParams, but still this doesn't feel right to write)


After some attempts I figured out that router.navigate([], {queryParams:{foo:42}}) works. This feels way better.

But I'm still not sure if that's the right way. Or if I missed some method for this.


How do you change your queryParams?

like image 950
Benjamin M Avatar asked Sep 08 '16 22:09

Benjamin M


1 Answers

If you look into Router class declaration you can find that:

Navigate based on the provided array of commands and a starting point. If no starting route is provided, the navigation is absolute.

Also it returns promise with value if navigation was successful or not.

navigate(commands: any[], extras?: NavigationExtras): Promise;

commands - array of commands to Router where to navigate;

extras - optional parameter where you specify additional properties like query parameters

If you look into NavigationExtras class you will find that not only you can specify query parameters to Router, but also set preserve previous query parameters etc.

I used navigate method like this:

this.router.navigate([], {
        queryParams: objectWithProperties,
        relativeTo: this.activeRoute
    });

where empty array means that location does not change and in extras i define query parameters using object with properties.

Angular resolves that object into something like this:

siteBasePath/routerDirectory?propertyName=propertyValue

Here are more useful information and examples which I found very useful: http://vsavkin.tumblr.com/post/145672529346/angular-router

I hope someone will find this useful.

like image 144
Imants Volkovs Avatar answered Nov 19 '22 05:11

Imants Volkovs