Twitter LogoFacebook Logo
Route Parameter - In Angular
Using route parameters to transfer data.
By: King

Route parameters are placeholders that we set in the web address of our app. It allows us to pass information through the web address. 


There are two types of parameters, (1) required and (2) optional.

Required route parameters are set as part of the path. 

www.codeible.com/tutorial/294


{ path: "tutorial/:id", component: ...}

Optional route parameters are added as part of the web address when we transition from one route to another.

www.codeible.com/...;theme=dark

Let’s see how they work in code, open your Angular project on VS code. 


To begin, create a component call RoutingExample by using the ng generate component command.

ng generate component RoutingExample

Make sure to have the router-outlet tags in app component html page.

<router-outlet></router-outlet>

Go to the app routing module and declare a route, use exampleRoute/name for the path and the RoutingExample component for the component.

const routes: Routes [] = [

   { path: "exampleRoute/name", component: RoutingExampleComponent }
];

If we take a look at the path, the path is static. We must go to localhost:4200/exampleRoute/name to activate the route.


What if we want to use John or some other name instead of name? We will have to add more paths and create more components.

const routes: Routes [] = [

   { path: "exampleRoute/name", component: RoutingExampleComponent },
   { path: "exampleRoute/John", component: RoutingExampleComponent },
   { path: "exampleRoute/Jen", component: RoutingExampleComponent }
];

Instead of using static paths, we can add a parameter to the path and create a custom syntax for our route. 

const routes: Routes [] = [

   { path: "exampleRoute/:name", component: RoutingExampleComponent },
];

This way, as long as what we put in the web address matches the format of the path, it will activate the route. We can use localhost:4200/exampleRoute/John... /Kelly... /Jenny and so on. All of these variation matches the syntax of the path. 

Let’s verify that. Save the project and start the local server. Then, open the browser and go to localhost:4200/exampleRoute/John. Then use Kelly.

Image from Codeible.com

As you can see, even though we did not define those routes, it still worked because we create a path that will get activated as long as it starts with exampleRoute and / whatever.

Let’s see how we can get the value of the parameter. 

Retrieving the Parameter Value

Go back to VS Code and go to the example route component TypeScript file. Then add ActivateRoute to the imports and inject it into the constructor of the component.

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


....

export class RoutingExampleComponent .... {

   constructor(private route: ActivatedRoute ){

   }

}

Inside the object, there is a property call params that we can subscribe to. It returns an object with all the parameters.

constructor(private route: ActivatedRoute ){
   this.route.params.subscribe(
      paramsObject => {

      }
   );
}

Since our parameter is call name, we can get the value by grabbing the paramsObject and accessing the name property.

this.route.params.subscribe(
   paramsObject => {
       paramsObject.name;
   }
);

If we take a look at the ExampleRoute html page. We’re displaying a static message. Replace it with an interpolation statement and pass in a variable. 

<p>{{name}}</p>

Go back to the component TypeScript file and declare the variable. Then Assign it with the parameter value.

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


....

export class RoutingExampleComponent .... {

   name: string;

   constructor(private route: ActivatedRoute ){

         this.route.params.subscribe(
              paramsObject => {
                  this.name = paramsObject.name;
              }
         );

   }

}

Now when we go to localhost:4200/exampleRoute/whatever, it will display whatever value we placed in parameter of the path.

Image from Codeible.com

Optional Parameters

Earlier in the video, we said that optional parameters are key and value pairs that are added to the web address when we transition from on route to another. 

localhost:4200/exampleRoute/whatever;age=10; gender=male

Each parameter is separated by a semi colon so we have 2 optional parameters: age and gender.

The paramsObject in the params subscription also contains all the optional parameters So we can grab the paramsObject and access the age and gender parameters.

this.route.params.subscribe(
   paramsObject => {
       this.name = paramsObject.name;

       paramsObject.age;
       paramsObject.gemder;

   }
);

Declare 2 variables to store the age and gender value and then go to the ExampleRoute component html page and insert the age and gender.

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


....

export class RoutingExampleComponent .... {

   name: string;
   age: number;
   gender: string;
   constructor(private route: ActivatedRoute ){

         this.route.params.subscribe(
              paramsObject => {
                  this.name = paramsObject.name;
                  this.age = paramsObject.age;
                  this.gender = paramsObject.gender;
              }
         );

   }

}

<p>{{name}}</p>

<p>{{age}}</p>
<p>{{gender}}</p>

Save the project and go to the browser.

Image from Codeible.com

As you can see, it is displaying the age and gender that we placed in the web address. However, we manually typed it in. Let’s see how we can add parameters in code.

Add a button and label it Optional Params in the app component html page. Then add the routerLink attribute directive.

<router-outlet></router-outlet>

<button routerLink="">Optional Params</button>

Normally to transition to another route, we would put the path that we want. But in order to add the parameters, we need to use the compact syntax and provide an array. 

<button [routerLink]="[]">Optional Params</button>

Each element in the array represents an extension. So we can put exampleRoute and John to represent exampleRoute/John


If we want to add the optional parameters, we need to pass in an object and then put all the parameters we want inside. 

<button [routerLink]="['exampleRoute', 'John', { age: 10, gender: 'male'} ]">Optional Params</button>

Save the project, go to the browser, and then go to localhost:4200 to reset the web address. Lastly, click on the button. 

Image from Codeible.com

Using the Router object

Instead of using the routerLink attribute directive, we can also use the router object. Go back to VS Code and add a click event to the button and give it a function to call.

<button 

(click)="optionalParams()"
[routerLink]="['exampleRoute', 'John', { age: 10, gender: 'male'} ]">
   Optional Params
</button>

Go to the app component TypeScript file. Add the router import and inject it into the constructor.

...
import { Router } from '@angular/router';

@Component({
...
})
export class AppComponent {

  constructor(private router: Router){ 

  }

}

Define the function for the click event and in the body of the function, grab the router object and call the navigate method.

optionalParams() {

   this.router.navigate();
}

The navigate method takes in an array that works the same way as our routerLink attribute so we can copy the contents and paste it inside the array.

optionalParams() {

   this.router.navigate(
      'exampleRoute', 'John', { age: 10, gender: 'male'} 
   );
}

Go to the app component HTML page and remove the routerLink attribute directive from the button. 

<button (click)="optionalParams()">

   Optional Params
</button>

Save the project and go to the browser. Go to localhost:4200 to reset it again. Then click on the button.

Image from Codeible.com

As you can see it worked the same way.

Recap

Let’s take a moment to recap what we have learned.

1. We learned that route parameters are values we set in the web address and that there are 2 types of route parameters: required and optional.

2. Required parameters are parameters we set in the path of the route and optional parameters are parameters we add to the web address.

3. We learned how to add a parameter in the path by using the colon symbol.

4. And we also learned how to add optional parameters to our web address when we transition from one page to another by using the router link attribute directive and the route object.


Sign In