Angular Routing Parameters (Required Param,Optional param,QueryParam,NavigationExtras)
Lets Discuss Angular Routing Parameters :-
- Required Parameters
- Optional Parameters
- Query Parameters
- Navigation Extras
Required Parameters :-
Required Route Parameters is used in pattern matching of the route so syntax should be correct in path .
Prefer This Parameter when value is simple not complex and multiple parameters are not passed
Syntax : —
//Declaration
const appRoutes:Routes = [{path:employee/:id,component:abcComp}]
// Here id is added as required parameter //Implementation in Ts (typescript)
let id = 2 // It can be dynamic this.route.navigate(['employee',id])// Catching The Route Parameter in Ts
constructor (private route :ActivatedRoute){
}
let id = parseInt(this.route.snapshot.paraMap.get('id'))
Optional Parameter :-
These Parameter are used when they are optional and we need to pass complex and multiple parameters .
Optional parameter is not used in patter matching so we don’t need it to declare in routing path .
// Declaration
const appRoutes:Routes = [{path:employee,component:abcComp}]
// You dont need to set optional parameter in routing //Implementationthis.route.navigate(['employee',{name:'ab'}]) // You can add multiple by using ,separated key for example {name:'ab',id:'1'}// Catching constructor (private route :ActivatedRoute){
}
let name = this.route.snapshot.paraMap.get('name')
Query Parameters:-
They are used to pass complex parameters and they are not used in pattern matching so we don’t need it to declare in routing path .
// Declaration
const appRoutes:Routes = [{path:employee,component:abcComp}]
// You dont need to set Query parameter in routing// Implementation in Ts
this.route.navigate(['employee'],{queryParams:{name:'a'}})//queryParamsHandling='Merge' or 'retain' these options is also used to retain the parameters or to merge them // Catching in Ts constructor(private route :ActivateRoute){
}
let name = this.route.snapshot.queryParamMap.get('name');
NavigationExtras :-
This New Method Cam After Angular 7.2.0
//Declaration
const appRoutes:Routes = [{path:employee,component:abcComp}]
// You dont need to set Extras in routing//Implementation In Ts
this.route.navigate(['employee'],{state:{name:'A'}})//Catching in Ts constructor (private router : Router){this.router.getCurrentNavigation().extras.state.name;
}// This works only in constructor it will not work on ngOnInit
If you have any question please ask in comment section .
Please Click on clap Button if you liked this article.