Manuel Mauky
Manuel Mauky

Reputation: 2193

Angular 2 Routing based on query params

Is it possible in Angular 2 to define routing based on query parameters? I'd like to have the following behaviour:

If the user enteres the url http:<server-path>/search I'd like to route to a StartPage component.

If the user enteres the url http:<server-path>/search?query=sometext I'd like to route to ResultList component.

I know that it's possible to use path parameters for routing but this is not what I like to do. I want to use query parameters if possible. I know how to trigger navigation in angular with query parameters but I don't know how to configure the Routes.

Upvotes: 15

Views: 15406

Answers (2)

BERGUIGA Mohamed Amine
BERGUIGA Mohamed Amine

Reputation: 6280

In the below code I'll show how to pass query string parameters across any route.

suppose we want to have the below url:

http://localhost:4200/myUrl?QueryParamEx=2258

In your constructor inject the ROUTER dependency

constructor(...private router: Router..){...}

The navigate function will allow us to navigate to the preceding url

goMyUrl() {
  this.router.navigate(['/myUrl'], { queryParams: { QueryParamEx: '2258' } });
}

Upvotes: 1

Teddy Sterne
Teddy Sterne

Reputation: 14221

So you can't define a path with the query string in it but you can use a route matcher instead and determine when to route to the ResultList component. You define this above the default route definition for search so that if the match fails it will default to the search route with no query string.

{
    component: ResultListComponent,
    matcher: (url: UrlSegment[]) => {
      console.log(url);
      return url.length === 1 && url[0].path.indexOf('search?query=') > -1 ? ({consumed: url}) : null;
    }
},
{
    path: 'search',
    component: SearchComponent,
}

Demo

Upvotes: 15

Related Questions