Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Angular 2 routing tutorial

Suggested Videos
Part 27 - Angular 2 http service tutorial | Text | Slides
Part 28 - Angular 2 http error handling | Text | Slides
Part 29 - Using Bootstrap with Angular 2 | Text | Slides

In this video we will discuss the basics of routing in Angular 2. Routing allows users to navigate from one view to another view.

At the moment, we have EmployeeListComponent in our application. Let's create another simple HomeComponent so we can see how to navigate from HomeComponent to EmployeeListComponent and vice-versa

Creating HomeComponent
1. Right click on the "app" folder and add a new folder. Name it "home". Right click on the "home" folder and add a new TypeScript file. Name it home.component.ts. Copy and paste the following code in it. Notice we have not included the 'selector' property in the @component decorator. The selector is only required if we are going to embed this component inside another component using the selector as a directive. Instead we are going to use the router to navigate to this component.

import { Component } from '@angular/core';

    template: '<h1>This is the home page</h1>'
export class HomeComponent {

2. In the application root module (app.module.ts) import HomeComponent and include it in the declarations array of @NgModule decorator.

import { HomeComponent } from './home/home.component';

    imports: [BrowserModule, FormsModule, HttpModule],
    declarations: [AppComponent, HomeComponent, ...],
    bootstrap: [AppComponent]

export class AppModule { }

If the user tries to navigate to a route that does not exist, we want to route the user to PageNotFoundComponent. So let's create this component as well.

Right click on the "others" folder and add a new TypeScript file. Name it pageNotFound.component.ts. Copy and paste the following code in it.

import { Component } from '@angular/core';

    template: '<h1>The page you are looking for does not exist</h1>'
export class PageNotFoundComponent {

Next, in the application root module (app.module.ts) import PageNotFoundComponent and include it in the declarations array of @NgModule decorator.

import { PageNotFoundComponent } from './Others/pageNotFound.component';

    imports: [BrowserModule, FormsModule, HttpModule],
    declarations: [AppComponent, PageNotFoundComponent, ...],
    bootstrap: [AppComponent]
export class AppModule { }

Here are the steps to implement routing in Angular 2 applications.

Step 1 : Set <base href> in the application host page which is index.html. The <base href> tells the angular router how to compose navigation URLs.

<base href="/src/">

Step 2 : In our angular application root module (app.module.ts), import RouterModule and Routes array and define routes as shown below.

import { RouterModule, Routes } from '@angular/router';

// Routes is an array of Route objects
// Each route maps a URL path to a component
// The 3rd route specifies the route to redirect to if the path
// is empty. In our case we are redirecting to /home
// The 4th route (**) is the wildcard route. This route is used
// if the requested URL doesn't match any other routes already defined
const appRoutes: Routes = [
    { path: 'home', component: HomeComponent },
    { path: 'employees', component: EmployeeListComponent },
    { path: '', redirectTo: '/home', pathMatch: 'full' },
    { path: '**', component: PageNotFoundComponent }

// To let the router know about the routes defined above,
// pass "appRoutes" constant to forRoot(appRoutes) method
    imports: [
        BrowserModule, FormsModule, HttpModule,
    declarations: [AppComponent, HomeComponent, …],
    bootstrap: [AppComponent]
export class AppModule { }

Important: The order of the routes is very important. When matching routes, Angular router uses first-match wins strategy. So more specific routes should be placed above less specific routes. In the configuration above, routes with a static path are listed first, followed by an empty path route, that matches the default route. The wildcard route comes last because it matches every URL and should be selected only if no other routes are matched first.

Step 3 : Tie the routes to application menu. Modify the root component (app.component.ts) as shown below. The only change we made is in the inline template.
  • We are using Bootstrap nav component to create the menu. We discussed Bootstrap nav component in Part 27 of Bootstrap tutorial.
  • The routerLink directive tells the router where to navigate when the user clicks the link.
  • The routerLinkActive directive is used to add the active bootstrap class to the HTML navigation element whose route matches the active route.
  • The router-outlet directive is used to specify the location where we want the routed component's view template to be displayed.
  • The routerLink, routerLinkActive and router-outlet directives are provided by the RouterModule which we have imported in our application root module.
  • If you forget to specify the router-outlet directive, you will get and error stating - cannot find primary outlet to load component.
import { Component } from '@angular/core';

    selector: 'my-app',
    template: `
                    <div style="padding:5px">
                        <ul class="nav nav-tabs">
                            <li routerLinkActive="active">
                                <a routerLink="home">Home</a>
                            <li routerLinkActive="active">
                                <a routerLink="employees">Employees</a>
export class AppComponent {

Step 4 : Finally in web.config file of our angular application include the following url-rewrite rule to tell IIS how to handle routes. The match url, <match url=".*" />, will rewrite every request. The URL in <action type="Rewrite" url="/src/"/> should match the base href in index.html.

      <rule name="Angular Routes" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        <action type="Rewrite" url="/src/" />

If you do not have the above url rewrite rule, when you referesh the page you will 404 page not found error.

To use "hash style" urls instead of HTML5 style url's, you just need to make one change in app.module.ts file. Set useHash property to true and pass it to the forRoot() method as shown below.

RouterModule.forRoot(appRoutes, { useHash: true })

If you are using "hash style" routes, we don't need the URL rewrite rule in web.config file.

Angular 2 tutorial for beginners


  1. Hi sir
    Some times my routing is not working if i refresh the browser or press the link button
    Page is showing Empty and in Firebug Console angular module are not loaded
    if am clicking multiple times on the menu, then its load

  2. Perfect.. Thanks Venkat for such great and spontaneous efforts. Appreciated!!!


If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.