Introduction

In this section, we introduce how to include the Angular 2 Router and use it in your project.

Step 1: Add the Router bundle to <head>

Angular 2 has a module bundle for handling client side routing's, named Router. For the systems JS loader, Angular 2 provides a router bundle as a separate resource.

To start using this bundle, the first thing you need to do is update your html file, for example index.html, to include the bundle script. To do this, simply add another tag in the <head> tag that links to the path as the other angular 2 file.

<script src="/your_path/angular2/router.dev.js" type="text/javascript"><script>

The router.dev.js script is delivered as part of the angular package. So when you pull that down you have the router bundle script, it's just the matter of including it based on the module loading strategy you are on.

There are two more things that we need to do to set up the router bundle.

Step 2: Add base tag to <head>

You need a <base href="your_path"> in the <head> element of the index.html file. So we can add a base tag and set the href attribute to a forward slash (/), this is used by the router to handle the application root path for routes.

<base href="/">

The other thing needed is to include ROUTER_PROVIDERS in the bootstrap call.

Step 3: Include ROUTER_PROVIDERS in bootstrap() call

The last step is to include ROUTER_PROVIDERS in bootstrap() call.

So for example in the main.ts file, you need to add a new import statement and import ROUTER_PROVIDERS from angular2/router

import {ROUTER_PROVIDERS} from 'angular2/router'

Then, add it to the providers array in the bootstrap() call, this will make Angular class like Router available to the app from constructor injection.

bootstrap(AppComponent, [ROUTER_PROVIDERS]);