Learn Angular 4.0 In 10 Days - Route Process - Day Nine

Let us start day 9 of the "Learning Angular 4.0 in 10 Days" series. In the previous articles, we discussed Ajax Request handling in Angular 4.0. If you want to read the previous articles of this series, do visit the below links.

Angular 4.0 brings many improved modules to the Angular framework including a new router called the Component Router. The component router is a 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 the 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 allow users to share links with others.

Routing allows you to,

  • Maintain the state of the 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 the application is on the specific route
  • component - component to be rendered when the application is on the specific route
  • redirectTo - redirect 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 - an 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 redirect 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 define 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.

  1. <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.

What are Nested Child Routes?

Child/Nested routing is a powerful new feature in the new Angular router. We can think of our application as a tree structure, components nested in more components. We can think the same way with our routes and URLs.

So we have the following routes, / and /about. Maybe our about page is extensive and there are a couple of different views we would like to display as well. The URLs would look something like /about and /about/item. The first route would be the default about page but more routes would offer another view with more details.

Defining Child Routes

When some routes may only be accessible and viewed within other routes it may be appropriate to create them as child routes.

For example: The product details page may have a tabbed navigation section that shows the product overview by default. When the user clicks the "Technical Specs" tab the section shows the specs instead.

If the user clicks on the product with ID 3, we want to show the product details page with the overview:

localhost:3000/product-details/3/overview

When the user clicks "Technical Specs":

localhost:3000/product-details/3/specs

overview and specs are child routes of product-details/:id. They are only reachable within product details. 

Passing Optional Parameters

Query parameters allow you to pass optional parameters to a route such as pagination information.

For example, on a route with a paginated list, the URL might look like the following to indicate that we've loaded the second page:

localhost:3000/product-list?page=2

The key difference between query parameters and route parameters is that the route parameters are essential to determining a route, whereas query parameters are optional.

Passing Query Parameters

Use the [queryParams] directive along with [routerLink] to pass query parameters. For example,
  1. <a [routerLink]="['product-list']" [queryParams]="{ page: 99 }">Go to Page 99</a>  

Alternatively, we can navigate programmatically using the Router service.

  1. goToPage(pageNum) {  
  2.     this.router.navigate(['/product-list'], { queryParams: { page: pageNum } });  
  3.   }  
Reading Query Parameters

Similar to reading route parameters, the Router service returns an Observable we can subscribe to in order to read the query parameters.

  1. import { Component } from '@angular/core';  
  2. import { ActivatedRoute, Router } from '@angular/router';  
  3.   
  4. @Component({  
  5.   selector: 'product-list',  
  6.   template: `<!-- Show product list -->`  
  7. })  
  8. export default class ProductList {  
  9.   constructor(  
  10.     private route: ActivatedRoute,  
  11.     private router: Router) {}  
  12.   
  13.   ngOnInit() {  
  14.     this.sub = this.route  
  15.       .queryParams  
  16.       .subscribe(params => {  
  17.         // Defaults to 0 if no query param provided.  
  18.         this.page = +params['page'] || 0;  
  19.       });  
  20.   }  
  21.   
  22.   ngOnDestroy() {  
  23.     this.sub.unsubscribe();  
  24.   }  
  25.   
  26.   nextPage() {  
  27.     this.router.navigate(['product-list'], { queryParams: { page: this.page + 1 } });  
  28.   }  
  29. }  
Sample Code of app.staticroute.module.ts
  1. import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';  
  2. import { APP_BASE_HREF } from '@angular/common';  
  3. import { BrowserModule } from '@angular/platform-browser';  
  4. import { FormsModule } from "@angular/forms";  
  5.   
  6. import { routing, appRoutingProviders } from './day4/route/route_config/static/app.routes';  
  7. import { HomePageComponent } from './day4/route/route_config/static/app.component.homepage';  
  8. import { HomeComponent } from './day4/route/route_config/static/app.component.home';  
  9. import { FirstProgComponent } from './day1/component/app.component.firstprog';  
  10. import { HelloWorldComponent } from './day1/component/app.component.helloworld';  
  11. import { TemplateUrlStyleComponent } from './day1/component/app.component.templatestyle';  
  12.   
  13.   
  14. @NgModule({  
  15.     imports: [BrowserModule, FormsModule, routing],  
  16.     declarations: [HomePageComponent, HomeComponent, HelloWorldComponent, FirstProgComponent, TemplateUrlStyleComponent],  
  17.     bootstrap: [HomePageComponent],  
  18.     schemas: [NO_ERRORS_SCHEMA],  
  19.     providers: [{ provide: APP_BASE_HREF, useValue: '/' }, appRoutingProviders],  
  20. })  
  21.   
  22. export class StaticRouteModule { }  
Sample Code of main.ts
  1. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';  
  2. import { StaticRouteModule } from './app.staticroute.module';  
  3.   
  4.   
  5. platformBrowserDynamic().bootstrapModule(StaticRouteModule);  
Sample Code of app.staticroute.module.html
  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <!--<base href="/">-->  
  5.     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  6.     <meta charset="utf-8">  
  7.     <title>Angular 2 - Console</title>  
  8.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  9.     <meta name="description" content="">  
  10.     <meta name="keywords" content="">  
  11.     <meta name="author" content="">  
  12.   
  13.     <link href="resource/css/bootstrap.min.css" rel="stylesheet">  
  14.     <link rel="stylesheet" href="resource/css/font-awesome.min.css">  
  15.     <link rel="stylesheet" href="resource/css/jquery-ui.css">  
  16.     <link href="resource/css/style.css" rel="stylesheet">  
  17. </head>  
  18. <body>  
  19.     <home-page></home-page>  
  20.     <footer>  
  21.         <div class="container">  
  22.             <div class="row">  
  23.                 <div class="col-md-12">  
  24.                     <p class="copy">Copyright © 2017-2018 | <a href="http://www.c-sharpcorner.com/members/debasis-saha">Debasis Saha</a> </p>  
  25.                 </div>  
  26.             </div>  
  27.         </div>  
  28.     </footer>  
  29.     <script src="resource/js/jquery.js"></script>  
  30.     <script src="resource/js/bootstrap.min.js"></script>  
  31.     <script src="resource/js/jquery-ui.min.js"></script>  
  32.     <script src="resource/js/jquery.slimscroll.min.js"></script>  
  33.     <script src="resource/js/custom.js"></script>  
  34.   
  35.     <script src="node_modules/core-js/client/shim.min.js"></script>  
  36.     <script src="node_modules/zone.js/dist/zone.js"></script>  
  37.     <script src="node_modules/systemjs/dist/system.src.js"></script>  
  38.     <script src="systemjs.config.js"></script>  
  39.     <script>  
  40.         System.import('main.js').catch(function (err) { console.error(err); });  
  41.     </script>  
  42.   
  43.     <!-- Set the base href, demo only! In your app: <base href="/"> -->  
  44.     <script>document.write('<base href="' + document.location + '" />');</script>  
  45. </body>  
  46. </html>  
Sample Code of app.component.home.ts
  1. import { Component, OnInit, ViewChild } from '@angular/core';  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: 'home',  
  6.     template: 'Angular Samples Home Page'  
  7. })  
  8.   
  9. export class HomeComponent implements OnInit {  
  10.    constructor() {  
  11.           
  12.     }  
  13.   
  14.     ngOnInit(): void {  
  15.     }  
  16.   
  17. }  
Sample Code of app.component.homepage.ts
  1. import { Component, OnInit } 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. }  
Sample Code of app.routes.ts 
  1. import { Routes, RouterModule } from '@angular/router';  
  2. import { HomeComponent } from './app.component.home';  
  3. import { FirstProgComponent } from '../../../../day1/component/app.component.firstprog';  
  4. import { HelloWorldComponent } from '../../../../day1/component/app.component.helloworld';  
  5. import { TemplateUrlStyleComponent } from '../../../../day1/component/app.component.templatestyle';  
  6.   
  7.   
  8. export const routes: Routes = [  
  9.     { path: '', redirectTo: 'home', pathMatch: 'full' },  
  10.     { path: 'home', component: HomeComponent },  
  11.     { path: 'hello', component: HelloWorldComponent },  
  12.     { path: 'firstprog', component: FirstProgComponent },  
  13.     { path: 'template', component: TemplateUrlStyleComponent }  
  14.   
  15. ];  
  16.   
  17. export const appRoutingProviders: any[] = [];  
  18.   
  19. export const routing = RouterModule.forRoot(routes);  
Sample Code of app.component.firstprog.ts
  1. import { Component } from "@angular/core";  
  2.   
  3. @Component({  
  4.     selector: "first-prog",  
  5.     template: "<h1>First Programe in Angular 4.0. Welcome to Day 1 Session</h1> "  
  6. })  
  7.   
  8. export class FirstProgComponent {  
  9.     constructor() {  
  10.     }  
  11. }  
Sample Code of app.component.helloworld.ts
  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     selector: 'hello-world',  
  5.     template: '<h1><b>Angular 4!</b>Hello World</h1>'  
  6. })  
  7.   
  8. export class HelloWorldComponent {  
  9.     constructor() {  
  10.     }  
  11.   
  12.     ngOnInit() {  
  13.         alert("Page Init Method Fired!!")  
  14.     }  
  15. }  
Sample Code of app.component.templatestyle.ts
  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: 'template-style',  
  6.     templateUrl: 'app.component.template.html',  
  7.     styles: ['h1{color:red;font-weight:bold}','h2{color:blue}']  
  8. })  
  9.   
  10. export class TemplateUrlStyleComponent {      
  11.     constructor() {  
  12.   
  13.     }  
  14. }  
Sample Code of app.component.template.html 
  1. <div>  
  2.         <h1>Angular 4 Component with Template</h1>  
  3.         <br />  
  4.         <h2>C# Corner</h2>  
  5. </div>  

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now