Basic Routing in Angular 2



Introduction

Today in the series Learning angular 2 step by step, we will learn about angular 2 basic routing.

You might be thinking that why basic, right?

In this series, we are learning angular 2 step by step and currently, we are at early stage of learning Angular 2. So, Here we will learn setup basic routing in angular 2 to make it easier to understand, especially for beginners.

Routing is one of the most important parts of developing a single page application in angular 2 and there are many things to learn in the routing. But here in this tutorial, we will learn setup basic routing in our Angular 2 application and later we will learn about advanced routing in Angular 2. OK?

Before reading this article, I would recommend reading my previous tutorial where I have explained about Angular 2 Component.


Let's start with structural directives.

So what is routing and why it's needed? 

In Angular 2 “everything is a component.” That's why Angular 2 is also called a component-based framework. Creating Angular 2 application means creating Angular 2 small small reusable components and each component has its own functionality. Like we have EmployeeList component for showing list of employees, we have searchbar component for enabling searching, and we will add more component here like Dashboard Component for showing quick info, EmployeeDetails component for showing details information of an employee and more in our application.

Now the question is how users will be navigated to a particular component based on their interaction such as when they click on a menu or button or something else.

Let me give you 1 example, suppose we have an angular2 application where we have Dashboard component, EmployeeList component, EmployeeDetails component and more... So, we should not show all the components in a single page, right? then how the users will switch out to different component based on their interaction?

We can do that with the help of routing. Routing allows us mapping a URL path to a component. So users can navigate to a different component by switching URLs.

Let's start setup basic routing in our angular 2 application. 

So, I will open the Application in VS Code Editor what we have created in the previous tutorial. Download the application if you want.

Create a new angular2 component, DashboardComponent

Here, First of all, I will create a new component which is Dashboard Component in our application and then we will setup basic routing where we will map '/dashbord' URL to our Dashboard component and '/employeelist' URL to the EmployeeList Component. And then we will see how to setup parameterize routing where we can pass some data to it.

So let's create the dashboard component first. and for this, I will create a folder here in this App folder.
right-click on the App folder inside the src folder > New Folder > enter folder name "Dashboard" and then inside this folder we will add a new typescript file.  So right-click on the Dashboard folder >  new file > Enter file name "dashboard.component.ts".


import {Component} from '@angular/core'
@Component({
    selector:'dashboard',
    templateUrl:'dashbaord.component.html',
    moduleId:module.id
})
export class DashboardComponent{
    public Title:string = 'Dashboard';
}

Now we are ready to setup our routing.

Set <base href>

First of all, we have to add an element to the index.html page. This is required as this tell the router how to compose navigation URLs. This base element should be the first element of the head tag. This tag indicates that this is a root URL of application which is served as a landing page.

Create a new file for define route definitions

Now we have to define route definition & configure Router for our application.

In angular 2, Routes is an object array of Route objects where we can map a URL path to a component. So when we will change browser's URL, the router will search for a corresponding Route using the URL from which it can determine the component to display.

Let's first define our application route definition. As our application grows, you'll define our application route definition into a separate file.

So I will create an another typescript file here in this App folder for define route definition.
Right-click on the App folder inside the src folder and then click on the new file menu. enter file name "app.route.ts".

import {Routes} from '@angular/router';
import {DashboardComponent} from './Dashboard/dashboard.component'
import {EmployeeListComponent} from './EmployeeList/employee-list.component'

export const MyAppRoutes: Routes = [    
    {path: 'dashboard', component: DashboardComponent},
    {path: 'employeelist', component: EmployeeListComponent}
]
You can see here we have imported Routes from '@angular/router' and also imported all the component that we want to map with a URL path. And then you can see in line 7, we have created an object of routes and in this object, we have defined our route for mapping URL path to a component.

Here we have defined 2 routes in our application, dashboard, and employeelist. So when we will go to the path '/dashboard' from a browser, the Dashboard component will be displayed and when we will go the path '/employeelist' then the employeeList component will be displayed.

Configure Router in app.module.ts file

We have done defining our routes. Now we have to configure the router via the RouterModule.forRoot method and then we have to import this into our bootstrap module for enabling routing in our application.
let's do it.

import { NgModule } from "@angular/core";
import {BrowserModule} from "@angular/platform-browser";
import {AppComponent} from "./app.component"
import {EmployeeListComponent} from './EmployeeList/employee-list.component'
import {SearchbarComponent} from './Shared/SearchBar/searchbar.component'
import {MyVisibilityDirective} from './Shared/MyVisibility/myvisibility.directive'
import {RangeRepeaterDirective} from './Shared/RangeRepeater/range-repeater.directive'

import {DashboardComponent} from './Dashboard/dashboard.component'
import {MyAppRoutes} from './app.routes'
import {RouterModule} from '@angular/router'

@NgModule({
    imports: [BrowserModule, RouterModule.forRoot(MyAppRoutes)],
    declarations: [AppComponent,EmployeeListComponent, SearchbarComponent,
    MyVisibilityDirective, RangeRepeaterDirective, DashboardComponent],
    bootstrap:[AppComponent]   
    //bootstrap:[EmployeeListComponent] 
})
export class AppModule{

}

What we have done here in line 9-11, we have imported the Dashboard Component and then we have imported our route definition from the file where we have defined our application routes and then we have imported RouterModule from '@angular/router'. In line 14, we have configured our router with the RouterModule.forRoot method. And in line 17, we have set the AppComponent in bootstrap for making it is a root component.

Update index.html page

As I have changed the root component to AppComponent, I have to update our index.html page also.

<!DOCTYPE html>
<html>
    <head>
        <base href="/">
        <title>This is my frist angular 2 app</title>
        <meta charset="utf-8"/>
        
        <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <link rel="stylesheet" href="./assets/mycss.css">
        <!-- 1. Load libraries -->
        <!-- Polyfill(s) for older browsers -->
        <script src="../node_modules/core-js/client/shim.min.js"></script>
        <script src="../node_modules/zone.js/dist/zone.js"></script>
        <script src="../node_modules/reflect-metadata/Reflect.js"></script>
        <script src="../node_modules/systemjs/dist/system.src.js"></script>
        <!-- System.JS configuration -->
        <script src="./Systemjs.config.js"></script> 
        <script>
            System.config({
                "defaultJSExtensions": true
            })

            System.import('app').catch(function(err){
                console.log(err);
            })

        </script>       
    </head>
    <body class="container">
        <app>Please Wait...</app>
        <!--<div class="row">
            <div class="md-col-12">
                <employee-list>Loading Employee List...</employee-list>
            </div>
        </div>-->
    </body>
</html>

Add a router-outlet tag in our root component template

We are almost done. Just a single step away from completing this. We have to add a RouterOutlet directive in our appcomponent template. RouterOutlet tells our router where to render the content in the view.
This is our appcomponent. Here I have added a router-outlet tag in the template So our router will render the component here to display.
import {Component} from '@angular/core';
@Component({
    selector:'app',
    template: `    
    <div class="container" style="padding-top:70px;">
        <router-outlet></router-outlet>
    </div>
    `
})
export class AppComponent{
    title:string = '';
    constructor(){
        this.title = 'Hello World';
    }
}

Run the application

For run the application go to View menu > click on Integrated Command > it will open the terminal > write npm start in the terminal and hit the enter key.

If everything you have done correctly, then the application should work perfectly as It's working fine to me for the /dashboard and /employeelist URL. But here I am getting 1 issue when we open the root URL (here in my case, http://localhost:3000), we are getting this error is because we have not defined any routing for this URL. Let's add a route for our root URL.

Update app.routes.ts

import {Routes} from '@angular/router';
import {DashboardComponent} from './Dashboard/dashboard.component'
import {EmployeeListComponent} from './EmployeeList/employee-list.component'
import {PageNotFoundComponent} from './PageNotFound/page-not-found.component'

export const MyAppRoutes: Routes = [
    {path: '', redirectTo:'/dashboard', pathMatch: 'full'},
    {path: 'dashboard', component: DashboardComponent},
    {path: 'employeelist', component: EmployeeListComponent},
    {path: '**', component: PageNotFoundComponent}
]
You can see here in line 7, we have added a route for root URL with an empty path and pathMatch:'full'. This pathMatch:'full' is required when we are defining a route with an empty path, otherwise the empty path will match with all routes.Here we have added redirectTo:'/dashboard', that means when we will visit the root URL of our application then we will be redirected to the /dashboard page. In line 10, we have added an another route with ** path. That means when no any matching path will be found in our routing that time this route will be select for executing.

You can see here, I have used a new component PageNotFoundComponent. Let's me quickly create the component

Create the PageNotFoundComponent component

We will Create a new folder "PageNotFound" first in the App Folder and then we will add a new typescript file here inside the "PageNotFound" folder.
Right-click on the App folder > New Folder > Enter folder name "PageNotFound" > Right click on the PageNotFound folder > New File > Enter file name "page-not-found.component.ts".
Write this below code.
import {Component} from '@angular/core'
@Component({
    selector:'pageNotFound',
    template:`
        <h1>{{Title}}</h1>
    `
})
export class PageNotFoundComponent{
    public Title:string = 'Page Not Found';
}

Now if you run the application, we will not get the error what we got last time for visit root URL. You can see that when we run the application, its automatically redirect to the dashboard page. And now if you try to go any invalid URL of the application then it will show the PageNotFound page. It's cool, right?

Setup parameterized routing

Now let me show you quickly how to set up parameterized routing in angular2. parameterized routing means we will be able to pass parameters in route.
So, what we will do here, we will create an another component employee details component for showing employee details when anyone will click on employee link of this employee-list component.

So for showing employee details in another component, we need to pass employee id in route parameter right? Ok, let's do this.

Create EmployeeDetailsComponent for showing details of an employee

Now I will create an another component which is EmployeeDetailsComponent for showing employee details information. I will create this for showing you how we can implement parameterize route for passing data in route parameter and capture the data from route parameters.

I think the name of the EmployeeList folder should be Employee right?  let's leave it as it is now. later we will change this name. Ok.

For adding the EmployeeDetailsComponent, we will create a new file here in the EmployeeList folder.

Right-click on the EmployeeList from inside the src > App folder. click on New File > enter filename "employee-details.component.ts"
import { Component } from "@angular/core";
import {ActivatedRoute} from '@angular/router';

@Component({
    selector:'employee-details',
    template:`
        Showing employee details of ID : {{EmployeeID}}
    `
})
export class EmployeeDetailsComponent{
    public EmployeeID : number;
    constructor(private route: ActivatedRoute){
        this.route.params.subscribe(params=>{
            this.EmployeeID = params["id"];
        })
    }
}

You can see here in line 2, we have imported ActivatedRoute from '@angular/router'. This is required for getting route parameter data. See in line 12, we have written code for getting route parameter data. Here we got the id parameter. Now we can use this parameter for fetch data from remote server in a real application.

Run Application

For run the application go to View menu > click on Integrated Command > it will open the terminal > write npm start in the terminal and hit the enter key.<
 Live Demo Download

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.