Routing in Angular 2 :- Part 1

Ahteshamax
Posted by in Angular category on for Beginner level | Points: 250 | Views : 4403 red flag

In this article we will understand why do we need and use routing in Angular 2.
Recommendation
Read Learning Angular 2 for newbie – Part 1 before this article.

Even before we start agenda of the write-up which is routing and practical implementation of it first we will understand why do we need and use routing? So the answer to this question is that to achieve SPA(Single Page Application). The very next question which will arise in your mind would be what is SPA?

Without wasting much of your time and quickly coming onto the topic we will answer your question in brief as covering other topic would be out of scope of this write-up.

SPA stands for Single Page Application as the name says whole application will be loaded in a single page. A site page would be constructed with template where it will have fixed header, fixed footer and Menu bar either loading on left side or right side. Only the dynamic portion will be present on that page which be changed as per demand done by the user. So in short site with header, footer and Menu part which is part of that template and is common structure will load for the first time including the dynamic portion. After that, only portion which is kept dynamic will be changed as per the request or depending on the page where user is. Below is the pictorial image which shows website structure on the browser demonstrating concept of SPA.


Hope that concept of SPA is clearly understood by the reader. Here in this article we will achieve SPA using Routing. In this article we will practically see implementation of SPA using Router.

Please note that this article follows Learn Angular 2 – Part 2 so we will continue with editing existing project code used in Angular 2 - Part2.

UI Folder

Under UI folder do the following changes and create new html pages for “MasterPage.html”, “Supplier.html”. Keep “Customer.html” file unchanged.

MasterAngular.html

Rename existing “index.html” to “MasterAngular.html”.


MasterPage.html

Create a new html page with name “MasterPage.html” having code following in it under UI folder.This new “MasterPage.html” page will be created as common template with Logo, Menu and Footer as static part of the page and a portion in between which will load dynamic content. Create a table which will have a logo at the top next it will have Header. Following down below to it on the left side it will have Left Menu consisting of “Supplier” and “Customer” links. In order to achieve routing instead of having <a href> link it will have <a [routerLink] = “[‘Supplier’]”> as path to display and to open “Supplier.html” page and <a [routerLink] = “[‘Customer’]”> as display path and open “Customer.html” page when the link is clicked. Next to it will have the dynamic region when clicked by the user that requested page will be loaded within the tag <router-outlet></router-outlet>And at the last bottom “Footer” will be loaded.

<table border="1"><tr><td><img src="http://www.questpond.com/img/logo.
jpg" alt="Alternate Text" /></td><td>Header</td></tr>
<tr><td><u>Left Menu</u><br /><br /><br /><a 
[routerLink]="['Supplier']">Supplier</a><br /><br />
<a [routerLink]="['Customer']">Customer</a></td><td><router-outlet></router-
outlet></td></tr>
<tr><td>Footer</td><td></td></tr></table


Supplier.html

Next under UI folder create a new html page with name “Supplier.html”. This page will be loaded whenever “SupplierComponent” is called. This page will have a simple text which display’s following line

This is the suppliers page


Component

Next under Component folder create two TypeScript(.ts) files one with name
“MasterPageComponent.ts” and other with name “SupplierComponent.ts”

MasterPage Component

import {Component} from "@angular/core"

@Component({
    selector: "customer-ui",
    templateUrl: "../UI/MasterPage.html"
})
export class MasterPageComponent {
}

In “MasterPageComponent.ts” file will have only the selector: “customer-ui”


Supplier Component

Create SupplierComponent.ts with import “Component” from the core angular available under the path “@angular/core”

Here set template URL which will display Supplier.html whenever “SupplierComponent” is hit.

import {Component} from "@angular/core"

@Component({

    templateUrl: "../UI/Supplier.html"
})
export class SupplierComponent {
}

Remove “selector: customer-ui” from “SupplierComponent.ts” file as it will have only in MasterPage.html.


Also remove “selector: customer-ui” from “CustomerComponent.ts”file.


Routing

Now to do routing create a separate folder with name “Routing” under Explorer altogether for achieving Routing.

Under “Routing.ts” file import all the three components “CustomerComponent”, “SupplierComponent” and “MasterPageComponent”. And will be exposed outside using “export” and named as “ApplicationRoutes”.

import {Component} from '@angular/core';
import {CustomerComponent} from '../Component/CustomerComponent';
import {SupplierComponent} from "../Component/SupplierComponent";
import {MasterPageComponent} from "../Component/MasterPageComponent";
export const ApplicationRoutes = [
    { path: 'Customer', component: CustomerComponent },
    { path: 'Supplier', component: SupplierComponent },
     { path: 'UI/MasterAngular.html', component:CustomerComponent  }
];


Module

Now under the Module folder do the following changes in “MainModuleLibrary.ts” file. Import two new components, “MasterPageComponent” and “SupplierComponent” by specifying path of each of them. Then import “RouterModule” from “@angular/router” and finally importing “ApplicationRoutes” from the Routing file available under Routing folder.

Within @NgModule under imports specifying the RouterModule with the following syntax written

RouterModule.forRoot(ApplicationRoutes)

Under declarations specify “MasterPageComponent” and “SupplierComponent”.

And then under bootstrap set “MasterPageComponent”.

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {FormsModule} from "@angular/forms"
import { ReactiveFormsModule } from '@angular/forms';
import { CustomerComponent }   from '../Component/CustomerComponent';
import { SupplierComponent }   from '../Component/SupplierComponent';
import { MasterPageComponent }   from '../Component/MasterPageComponent';
import { RouterModule }   from '@angular/router';
import { ApplicationRoutes }   from '../Routing/Routing';   

@NgModule({
    imports: [RouterModule.forRoot(ApplicationRoutes), BrowserModule,
             FormsModule],
    declarations: [CustomerComponent,MasterPageComponent,SupplierComponent],
    bootstrap: [MasterPageComponent]
})
export class MainModuleLibrary { }


Once all the components, module and routing is configured now it is the time to run and check the application.

Run http-server

For that click on View option available under Menu bar and then click on “Integrated Terminal”. Once the window is open which is just like command prompt over here to run server we have to write command. So type “http-server” which will run the http server and will show the path and port below on which it is running.

Copy the path and paste it on the chrome browser address bar.


Afterwards press enter to execute it which will show all the folder and files of the routing project. Remember that our Routing will be running within “MasterAngular.html” so first we have to locate folder in which it is present. Here we have it in UI folder. Next is click on the UI which is the folder containing “MasterAngular.html”.

Once the UI folder is open click in “MasterAngular.html”.


After “MasterAngular.html” page is open, it loads MasterPage having logo at the top, header, and menu with “Customer” & “Supplier” links at the left and footer at the bottom. While within the dynamic region by default it loads “CustomerComponent” as you can see in the image down below. It happen because we have specified under “Routing.ts” file to load “CustomerComponent” whenever “UI/MasterAngular.html” page is open. If you see that “MasterAngular.html”


Now within Left Menu click on Supplier link which will open Supplier link in the address bar and load “Supplier.html” in the dynamic portion rest part which includes logo, Header, Left Menu and Footer portion will remain static.

This can be checked by opening the developer tool for that hit F12 on the browser. Then click “Network” tab once developer tool is open and then under it click on “Img” as shown in the image down below, it loads “logo.jpg” once.


Then click on “Customer” link in the Left Menu which will load “Customer.html” in the dynamic region and open “Customer” link in the address bar. Now if you see in developer tool under Network > Img you will still see only one “logo.jpg” loading which clearly states that logo, header, Left Menu and Footer is only loaded once while loading respective html page of the link present within Left Menu when clicked.

This practical demonstration fulfills what SPA says which we discussed it at the start of this article.


Nice we have completed theory and practical demonstrating SPA using Routing with hope that it is understood by the reader.It still has shortcoming which we will see in the next Routing article which is resolved by Dynamicrouting. We will show practical demonstration of it and also called Lazy Loading.

Below is step by step video from Angular 2 project series which is fully practical& easy to understand: -

Recommendation
Read Dynamic Routing in Angular 2 – Part 2 after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Ahteshamax
Full Name: Ahtesham Shaikh
Member Level: Bronze
Member Status: Member
Member Since: 10/3/2016 2:36:04 AM
Country: India
Ahtesham Shaikh
http://www.learnmsbitutorials.net/
Hey Friends, Myself Ahtesham a coder, writer & technical supporter for IT world and for my company Questpond. Having 10+ years of experience in microsoft technologies like WCF, WPF, MVC, Sharepoint, AngularJS, MSBI, Excel 2000 - 2013, Powerpoint, C#, SQL Server and so on. I just find myself happy and satisfy by doing this job. Apart from profession love reading novels and other digital network books. I'm a faculty at Questpond and do take trainings on c#, object oriented programming, msbi, sharepoint, mvc, mvc, angularJS and so on. Feel free get in touch me for one-to-one trainings, offline trainings @Andheri Mumbai, Online training via microsoft live meeting.

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)