Activated Route in Angular Environment

Posted By Mahima Gautam | 30-Dec-2018

We often need to have a variable in a path and we need to use it to make the route dynamic, a common example of this is an ID.

Let us say blog. Each article in our blog has an ID, the URLs for each blog article may look like

and so on...

Now, we could write a route for each article below:

const routes: Routes = [
 { path: 'blog/1', component: Blog1Component },
 { path: 'blog/2', component: Blog2Component },
 { path: 'blog/3', component: Blog3Component },
 { path: 'blog/4', component: Blog4Component },

But a better solution is to have 1 route with 1 component named blog component and pass a variable on BlogComponent the number part of the URL.

That is called parameterized route and we would implement it as below:

const routes: Routes = [
 { path: 'blog/:id', component: BlogComponent } 


a path has a variable called id, we know that it is a variable since it is starting with a colon :

A path can have multiple variables as long as they all start with: and have different names.

Non-parameterised routes always take priority on parameterized routes, so in the below code:

const routes: Routes = [
 { path: 'blog/:id', component: BlogComponent },
 { path: 'blog/moo', component: MooComponent },

If we visited /blog/moo the component will route is MooComponent even though it matches the path for the first path (blog/: id) route as well.

So how can we pass the blog component, the value of the id variable? If we visit (/blog/1) how does BlogComponent know the id is 1 and therefore to show the matching article. ActivatedRoute now comes into the picture.

We import it 1st and then we can inject it into the constructor of blog component. It shows Observable which we can subscribe to, like so:

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

constructor(private route: ActivatedRoute) {
    this.route.params.subscribe( params => console.log(params) );

Now if we navigate to '/blog/1', the number 1 would get emitted on the observable:

{ id: 1 }

Request for Proposal

Recaptcha is required.

Sending message..