AngularJS 2.0 From Beginning - Route Part One - Day Thirteen

I am here to continue the discussion around AngularJS 2.0. So far, we have discussed about data binding, input properties, output properties, pipes, viewchild, and also about directives in Angular 2.0. Now in this article, I will discuss about the route concept in Angular 2.0. Also, in case you did not have a look at the previous articles of this series, go through the links mentioned below.

In my previous article, I already discussed about the transclusation in Angular 2.0. In this article, we will discuss about the route concept in Angular 2.0.

Angular 2.0 brings many improved modules to the Angular framework including a new router called the Component Router. The component router is totally configurable and feature packed router. Features included are standard view routing, nested child routes, named routes, and route parameters.

Why Routing ?

Routing allows us to specify some aspects of the application's state in the URL. Unlike with Server-side front-end solutions, this is optional - we can build full application without ever changing the URL. Adding routing, however, allows the user to go straight into certain aspects of the application. This is very convenient as it can keep your application linkable and bookmarkable, and allows users to share links with others.

Routing allows you to -
  • Maintain the state of application
  • Implement modular applications
  • Implement the application based on the roles (certain roles have access to certain URLs)

Route Definition Objects

The Routes type is an array of routes that defines the routing for the application. This is where we can set up the expected paths, the components we want to use, and what we want our application to understand them as.

Each route can have different attributes. Some of the common attributes are.

  • Path - URL to be shown in the browser when application is on the specific route
  • Component - component to be rendered when the application is on the specific route
  • redirectTo - redirects route if needed; each route can have either component or redirect attribute defined in the route (covered later in this chapter)
  • pathMatch - optional property that defaults to 'prefix'; determines whether to match full URLs or just the beginning. When defining a route with empty path string set pathMatch to 'full', otherwise it will match all paths.
  • children - array of route definitions objects representing the child routes of this route (covered later in this chapter)

To use Routes, create an array of route configurations.

  1. const routes: Routes = [  
  2.   { path: 'component-one', component: ComponentOne },  
  3.   { path: 'component-two', component: ComponentTwo }  
  4. ]; 

RouterModule

RouterModule.forRoot takes the Routes array as an argument and returns a configured router module. The following sample shows how we import this module in an app.routes.ts file. 
  1. import { RouterModule, Routes } from '@angular/router';    
  2.     
  3. const routes: Routes = [    
  4.   { path: 'component-one', component: ComponentOne },    
  5.   { path: 'component-two', component: ComponentTwo }    
  6. ];    
  7.    
  8. export const routing = RouterModule.forRoot(routes);  
We, then, import our routing configuration in the root of our application.
  1. import { routing } from './app.routes';  
  2.   
  3. @NgModule({  
  4.   imports: [  
  5.     BrowserModule,  
  6.     routing  
  7.   ],  
  8.   declarations: [  
  9.     AppComponent,  
  10.     ComponentOne,  
  11.     ComponentTwo  
  12.   ],  
  13.   bootstrap: [ AppComponent ]  
  14. })  
  15. export class AppModule {  
  16.  

Redirecting the Router to Another Route

When your application starts, it navigates to the empty route by default. We can configure the router to redirect to a named route by default.

  1. export const routes: Routes = [  
  2.   { path: '', redirectTo: 'component-one', pathMatch: 'full' },  
  3.   { path: 'component-one', component: ComponentOne },  
  4.   { path: 'component-two', component: ComponentTwo }  
  5. ];   

The pathMatch property, which is required for redirects, tells the router how it should match the URL provided in order to redirect to the specified route. Since pathMatch: full is provided, the router will redirected to component-one if the entire URL matches the empty path ('').

When starting the application, it will now automatically navigate to the route for component-one.

RouterLink

Add links to routes using the RouterLink directive. For example, the following code defines a link to the route at path component-one.

  1. <a routerLink="/component-one">Component One</a>   

Alternatively, you can navigate to a route by calling the navigate function on the router.

  1. this.router.navigate(['/component-one']);   

Dynamically Adding Route Components

Rather than defining each route's component separately, use RouterOutlet which serves as a component placeholder; Angular dynamically adds the component for the route being activated into the <router-outlet></router-outlet> element.

<router-outlet></router-outlet>

In the above example, the component corresponding to the route specified will be placed after the <router-outlet></router-outlet> element when the link is clicked.

Now, to demonstrate the basic route, please see below.

app.component.cmputer.html
  1. <div class="panel-body">  
  2.     <table class="table table-striped table-bordered">  
  3.         <thead>  
  4.             <tr>  
  5.                 <th>Name</th>  
  6.                 <th>Company</th>  
  7.                 <th class="text-right">Quantity</th>  
  8.                 <th class="text-right">Price</th>  
  9.             </tr>  
  10.         </thead>  
  11.         <tbody>  
  12.             <tr *ngFor="let item of data">  
  13.                 <td>{{item.name}}</td>  
  14.                 <td>{{item.company}}</td>  
  15.                 <td class="text-right">{{item.quantity}}</td>  
  16.                 <td class="text-right">{{item.price | currency}}</td>  
  17.             </tr>  
  18.         </tbody>  
  19.     </table>  
  20. </div>   
app.component.computer.ts
  1. import { Component, OnInit, ViewChild } from '@angular/core';  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: 'computer',  
  6.     templateUrl: 'app.component.computer.html'  
  7. })  
  8.   
  9. export class ComputerComponent implements OnInit {  
  10.   
  11.     private data: Array<any> = [];  
  12.   
  13.     constructor() {  
  14.         this.data = [{ name: 'HP Pavilion 15"', company: 'HP', quantity: '10', price: '42000.00', specification: 'Intel Core i3 2 GB Ram 500 GB HDD with Windows 10' },  
  15.         { name: 'Lenovo Flex 2"', company: 'Lenovo', quantity: '20', price: '32000.00', specification: 'Intel Core i3 2 GB Ram 500 GB HDD with DOS OS' },  
  16.         { name: 'Lenovo Yova 500"', company: 'Lenovo', quantity: '20', price: '70000.00', specification: 'Intel Core i7 8 GB Ram 1TB HDD with Windows 8.1' }]  
  17.     }  
  18.   
  19.     ngOnInit(): void {  
  20.     }  
  21.   
  22. }   
app.component.mobile.html
  1. <div class="panel-body">  
  2.     <table class="table table-striped table-bordered">  
  3.         <thead>  
  4.             <tr>  
  5.                 <th>Name</th>  
  6.                 <th>Company</th>  
  7.                 <th class="text-right">Quantity</th>  
  8.                 <th class="text-right">Price</th>  
  9.             </tr>  
  10.         </thead>  
  11.         <tbody>  
  12.             <tr *ngFor="let item of data">  
  13.                 <td>{{item.name}}</td>  
  14.                 <td>{{item.company}}</td>  
  15.                 <td class="text-right">{{item.quantity}}</td>  
  16.                 <td class="text-right">{{item.price |currency:'INR':true}}</td>  
  17.             </tr>  
  18.         </tbody>  
  19.     </table>  
  20. </div>   
app.component.mobile.ts
  1. import { Component, OnInit, ViewChild } from '@angular/core';  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: 'mobile',  
  6.     templateUrl: 'app.component.mobile.html'  
  7. })  
  8.   
  9. export class MobileComponent implements OnInit {  
  10.   
  11.     private data: Array<any> = [];  
  12.   
  13.     constructor() {  
  14.         this.data = [{ name: 'Galaxy Tab 3', company: 'Samsung', quantity: '10', price: '25000.00' },  
  15.         { name: 'Galaxy Tab 5', company: 'Samsung', quantity: '50', price: '55000.00' },  
  16.         { name: 'G4', company: 'LG', quantity: '10', price: '40000.00' },  
  17.         { name: 'Canvas 3', company: 'Micromax', quantity: '25', price: '18000.00' }];  
  18.     }  
  19.   
  20.     ngOnInit(): void {  
  21.     }  
  22.   
  23. }   
app.component.tv.html
  1. <div class="panel-body">  
  2.     <table class="table table-striped table-bordered">  
  3.         <thead>  
  4.             <tr>  
  5.                 <th>Name</th>  
  6.                 <th>Company</th>  
  7.                 <th class="text-right">Quantity</th>  
  8.                 <th class="text-right">Price</th>  
  9.             </tr>  
  10.         </thead>  
  11.         <tbody>  
  12.             <tr *ngFor="let item of data">  
  13.                 <td>{{item.name}}</td>  
  14.                 <td>{{item.company}}</td>  
  15.                 <td class="text-right">{{item.quantity}}</td>  
  16.                 <td class="text-right">{{item.price | currency}}</td>  
  17.             </tr>  
  18.         </tbody>  
  19.     </table>  
  20. </div>   
app.component.tv.ts
  1. import { Component, OnInit, ViewChild } from '@angular/core';  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: 'tv',  
  6.     templateUrl: 'app.component.tv.html'  
  7. })  
  8.   
  9. export class TvComponent implements OnInit {  
  10.   
  11.     private data: Array<any> = [];  
  12.   
  13.     constructor() {  
  14.         this.data = [{ name: 'LED TV 20"', company: 'Samsung', quantity: '10', price: '11000.00' },  
  15.         { name: 'LED TV 24"', company: 'Samsung', quantity: '50', price: '15000.00' },  
  16.         { name: 'LED TV 32"', company: 'LG', quantity: '10', price: '32000.00' },  
  17.         { name: 'LED TV 48"', company: 'SONY', quantity: '25', price: '28000.00' }];  
  18.     }  
  19.   
  20.     ngOnInit(): void {  
  21.     }  
  22.   

app.component.home.html
  1. <div class="row">  
  2.     <div class="panel-body">  
  3.         Home Page  
  4.         <br />  
  5.         <h3 class="panel-heading"><span>{{message}}</span></h3>  
  6.     </div>  
  7. </div>  
app.component.home.ts
  1. import { Component, OnInit, ViewChild } from '@angular/core';  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: 'home',  
  6.     templateUrl: 'app.component.home.html'  
  7. })  
  8.   
  9. export class HomeComponent implements OnInit {  
  10.   
  11.     private message: string = '';  
  12.     constructor() {  
  13.         this.message = 'Click link to move other page';  
  14.     }  
  15.   
  16.     ngOnInit(): void {  
  17.     }  
  18.   
  19. }  
app.component.homepage.html
  1. <div class="rowDiv panel panel-primary">  
  2.     <h2 class="panel-heading">Demostration of Angular 2.0 Basic Route</h2>  
  3.     <table style="width:40%;">  
  4.         <tr class="table-bordered">  
  5.             <td><a routerLink="/home" class="btn-block">Home</a></td>  
  6.             <td><a routerLink="/mobile">Mobile</a></td>  
  7.             <td><a routerLink="/tv">TV</a></td>  
  8.             <td><a routerLink="/computer">Computers</a></td>  
  9.         </tr>  
  10.     </table>  
  11. </div>  
  12. <div class="rowDiv navbar-form">  
  13.     <router-outlet></router-outlet>  
  14. </div>    
app.component.homepage.ts
  1. import { Component, OnInit, ViewChild } from '@angular/core';  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: 'home-page',  
  6.     templateUrl: 'app.component.homepage.html'  
  7. })  
  8.   
  9. export class HomePageComponent implements OnInit {  
  10.   
  11.     constructor() {  
  12.     }  
  13.   
  14.     ngOnInit(): void {  
  15.     }  
  16.   
  17. }  
app.routes.ts
  1. import { Routes, RouterModule } from '@angular/router';  
  2. import { HomeComponent } from './app.component.home';  
  3. import { MobileComponent } from './app.component.mobile';  
  4. import { TvComponent } from './app.component.tv';  
  5. import { ComputerComponent } from './app.component.computer';  
  6.   
  7. export const routes: Routes = [  
  8.     { path: '', redirectTo: 'home', pathMatch: 'full' },  
  9.     { path: 'home', component: HomeComponent },  
  10.     { path: 'tv', component: TvComponent },  
  11.     { path: 'mobile', component: MobileComponent },  
  12.     { path: 'computer', component: ComputerComponent }  
  13.   
  14. ];  
  15.   
  16. export const appRoutingProviders: any[] = [  
  17.   
  18. ];  
  19.   
  20. export const routing = RouterModule.forRoot(routes);  
app.module.ts
  1. import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { FormsModule } from "@angular/forms";  
  4.   
  5. import { routing, appRoutingProviders } from './src/app.routes';  
  6. import { HomePageComponent } from './src/app.component.homepage';  
  7. import { HomeComponent } from './src/app.component.home';  
  8. import { MobileComponent } from './src/app.component.mobile';  
  9. import { TvComponent } from './src/app.component.tv';  
  10. import { ComputerComponent } from './src/app.component.computer';  
  11.   
  12. @NgModule({  
  13.     imports: [BrowserModule, FormsModule, routing],  
  14.     declarations: [HomePageComponent, HomeComponent, MobileComponent, TvComponent, ComputerComponent],  
  15.     bootstrap: [HomePageComponent],  
  16.     schemas: [NO_ERRORS_SCHEMA],  
  17.     providers: [appRoutingProviders],  
  18. })  
  19. export class AppModule { } 
main.ts
  1. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';  
  2.   
  3. import { AppModule } from './app.module';  
  4.   
  5. const platform = platformBrowserDynamic();  
  6. platform.bootstrapModule(AppModule); 
 index.html
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title>Angular2 - Basic router example</title>  
  5.     <meta charset="UTF-8">  
  6.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  7.     <link href="../resources/style/bootstrap.css" rel="stylesheet" />  
  8.     <link href="../resources/style/style1.css" rel="stylesheet" />  
  9.     <!-- Polyfill(s) for older browsers -->  
  10.     <script src="../resources/js/jquery-2.1.1.js"></script>  
  11.     <script src="../resources/js/bootstrap.js"></script>  
  12.   
  13.     <script src="../node_modules/core-js/client/shim.min.js"></script>  
  14.     <script src="../node_modules/zone.js/dist/zone.js"></script>  
  15.     <script src="../node_modules/reflect-metadata/Reflect.js"></script>  
  16.     <script src="../node_modules/systemjs/dist/system.src.js"></script>  
  17.     <script src="../systemjs.config.js"></script>  
  18.     <script>  
  19.         System.import('app').catch(function (err) { console.error(err); });  
  20.     </script>  
  21.     <!-- Set the base href, demo only! In your app: <base href="/"> -->  
  22.     <script>document.write('<base href="' + document.location + '" />');</script>  
  23. </head>  
  24. <body>  
  25.     <home-page>Loading</home-page>  
  26. </body>  
  27. </html> 
Now, run the code. The output is shown below.
 

Up Next
    Ebook Download
    View all
    Learn
    View all