Query Params:
Simple example
<a [routerLink]="['product']" [queryParams]="{ page:2 }">Page 2</a>
The router will construct the URL as /product?pageNum=2
<a [routerLink]="['product']" [queryParams]="{ val1:2 , val2:10}">Whatever</a>
The router will construct the URL as /product?val1=2&val2=10
Programatically also we can pass queryparams
this.router.navigate(['/product'], { queryParams: { page: pageNum } });
here router is of type Router
import { Router } from '@angular/router';
Reading QueryParams
this.sub = this.Activatedroute.queryParamMap
.subscribe(params => {
this.pageNum = +params.get('pageNum')||0;
});
this.Activatedroute.snapshot.queryParamMap.get('pageNum')||0
why snapshot and subscribe and what is difference between them
Remember, the router populates the snapshot, when the component loads for the first time. Hence you will read only the initial value of the query parameter with the snapshot property. You will not be able to retrieve any subsequent changes to the query parameter.
query Params Handling
We have three options to handle these query params they are
Preserve - The Angular preserves or carry forwards the query parameter of the current route to next navigation. Any query parameters of the next route are discarded
Merge - The Angular merges the query parameters from the current route with that of next route before navigating to the next route.
Null - This is default option. The angular removes the query parameter from the URL, when navigating to the next..
Navigate between Routes
We are having 2 ways to navigate Around different routes
Which is one by
and other would be programatic navigation
this._router.navigate(['product/detail/1']
this._router.navigateByUrl('product')
this._router.navigate(['detail'], { queryParams: { pageNum: this.pageNum + 1 }, relativeTo: this._Activatedroute } );
.navigate or .navigateByurl both always uses absolute path
So what is difference between absolute and relative path
absolute contains a / before route like /about
absolute path always appends to the base url like in our case locally it would be
localhost:4000/about
Relative path does not contain a / before it appends the url to currently activates route
if you are in page localhost:4000/career then it would append to this as localhost:4000/career/about
Folder Structure
./ ../ .../ these type of routes can also be used these comes under relative paths and not as absolute paths
this would navigate like
./ - appends given route one level up
../ - appends given route 2 level up
example :
active route is - localhost:4200/about
./home - localhost:4200/about/home
../home - localhost:4200/home
Top comments (0)