Search code examples
angularangular-router

Angular 4 Query Params without Route params


This works (with Route Params = :id)

{
    path: 'qp/:id?repo=1',
    component: QueryParamsComponent
}

<li><a [routerLink]="['/qp', 5]" [queryParams]="{repo:1}">Query Params</a></li>

but without Route Params, it does'nt work,

Is there a way to make below code work?

{
    path: 'qp?repo=1',
    component: QueryParamsComponent
}

<li><a [routerLink]="['/qp']" [queryParams]="{repo:1}">Query Params</a></li>

Or any other way to achieve this?

This is my QueryParamsComponent

repo = ' ';
ngOnInit() {
  this.router.params.subscribe((params: Params) => {
    this.repo = params['repo'];
  });
}

Angular Version: 4.2.4


Solution

  • You can define multiple routes with or without parameter calling the same component and you don't need to put your queryParams in your routes config:

    {
     path: 'qp/:id,
     component: QueryParamsComponent
    },
    {
      path: 'qp',
      component: QueryParamsComponent
    }
    

    and inside your component :

    this.router.queryParams.subscribe(params => {
        this.repo= +params['repos'];
     })