query params are missing from the url in angular 6

Viewed 4309

The url entered directly is not showing the query parameters in the url.

i have given my route path as:

{ path: 'userdetails/:id', component: userdetailscomponent}

And my url is need to work as

https://www.(site).com/userdetails?id=5.

But the url is working as:

https://www.(site).com/userdetails

The query params is not showing when the url is directly opened in the browser. The query params are disappearing and the url is going to main route with out query param .How can i get the query param to work and is their any way to get the lost query params?

1 Answers

Try this type of approach. stackblitz example

Use this way for query parameters

{ path: "userdetails", component: UserDetailsComponent}

In your typescript file

import {ActivatedRoute} from '@angular/router';

userId;
constructor(private activatedRoute: ActivatedRoute) { }

ngOnInit() {
  this.activatedRoute.queryParams.subscribe(params => {
    this.userId = params['id'] || 0;
  });
}

In your html file

<div *ngIf="userId; else userDetail">
   <h2>User Details for the user with id {{userId}}</h2>
</div>

<ng-template #userDetail>
   User Details Component
</ng-template>

How to use this

Here sends query param id value as 15
<a [routerLink]="['/userdetails']" [queryParams]="{ id: 15}">User Details 
 with query parameter</a>

Without query parameters 
<a [routerLink]="['/userdetails' ]">User Details</a>
Related