Angular Routing Parameter

·

2 min read

Four way we can use angular routing parameters

  1. Required Parameters
  2. Optional Parameters
  3. Query Parameters
  4. Navigation Extras

Required Parameters :-

The required parameter is mandatory inside the route path.

Prefer This Parameter when value is simple not complex and multiple parameters are not passed.

e.g. -

//Declaration
   const appRoutes:Routes = [{path:product/:productId, component: ProductComp}]

// Here productId is added as required parameter 
// Implementation
   let productId = 2 // It can be dynamic 
   this.route.navigate(['product', productId])

// Getting
   constructor (private route :ActivatedRoute){
   }
   let productId= parseInt(this.route.snapshot.paraMap.get('productId'))

Optional Parameters :-

Optional parameters are not mandatory inside the route path. The routing path matching not required here.

e.g. -

// Declaration 
    const appRoutes:Routes = [{path:product,component:ProductComp}]

// You don't need to set optional parameter in routing 
// Implementation
    this.route.navigate(['product', {name:'Monitors'}]) 

// You can add multiple by using ,separated  key for example {name:'xxx',id:'1'}

// Getting
    constructor (private route :ActivatedRoute){
    }

  let name = this.route.snapshot.paraMap.get('name');

Query Parameters :-

Query parameters are different from regular routes parameter. We can use query parameter for passing optional parameters across any route in the application.

e.g. -

// Declaration 
   const appRoutes:Routes = [{path:product,component:ProductComp}]
// You don't need to set Query parameter in routing

// Implementation
   this.route.navigate(['product'],{queryParams:{name:'monitors'}})

// queryParamsHandling='Merge' or 'retain' these options is also used to retain the parameters or to merge them 

// getting
   constructor(private route :ActivateRoute){
    }
    let name = this.route.snapshot.queryParamMap.get('name');

Navigation Extras :-

New methods introduce angular. Here we can pass data in angular route very easily. Navigation extras interface provides various properties and methods - Interface -

interface NavigationExtras extends UrlCreationOptions, NavigationBehaviorOptions {

  // inherited from router/UrlCreationOptions
  relativeTo?: ActivatedRoute | null
  queryParams?: Params | null
  fragment?: string
  queryParamsHandling?: QueryParamsHandling | null
  preserveFragment?: boolean

  // inherited from router/NavigationBehaviorOptions
  skipLocationChange?: boolean
  replaceUrl?: boolean
  state?: {...}
}

e.g. -

// Declaration
   const appRoutes:Routes = [{path:product,component:ProductComp}]

// You dont need to set Extras in routing
// Implementation
   this.route.navigate(['product'],{state:{name:'mobiles'}})

// Getting
  constructor (private router : Router){
      this.router.getCurrentNavigation().extras.state.name;
   }