Angular 2 – The New Router

Hi Friends,

Hope you are well. Angular 2 team has released a new router lately to be used along with their RC versions. This kinda makes the old router obsolete and so I decided to post a new post on using this new router in your Angular 2 apps.

Let’s begin.

A screencast of this post:

The complete code for this post is available here.

Let’s create a new app using the angular-cli tool. Open up a terminal and give the below command.

Now open up the app in a editor of your choice.

Okay. As of now the generator for routes is disabled in the cli tool due to the new changes in the router. So we have to wire up our routes manually.

Inside the src -> app directory create a new file called app.routes.ts.

This is where we will be writing all our route configurations. It is completely independent of the appcomponent and is bootstrapped so as to ensure its availability throughout the app.

Now create two new components using the below commands.

This will generate two different components for our app which we will use as 2 different screens for which we require routing.

Open up app.routes.ts and add the below code.


The above code is pretty much self explanatory. I am simply exporting a const variable that contains the route configurations. Please note that we don’t use name property anymore.

Now open up index.ts (in the app directory) and add our app.routes.ts file as well as shown below.

Open up main.ts and bootstrap our AppRouterProvider.

Now we have configured routes. Let us enable a couple of links for naviagation. Open up app.component.html and add the below code.

As you could I am using routerLink and giving the paths here directly (we are not using the name property in our new router). Router outlet simply signifies where I want to place my injected views.

Now just serve the app using the below command.

You would see a screen as shown below.


Clicking on the links would take you to the pages respectively thereby showing that routing works. Similarly you could handle routing in your application.

Hope this helped you guys. In my next post I will elaborate on how to do authentication with guarded routes in your apps.

Thanks for reading guys. Peace.. :)