Custom validation in angular

Updated : Nov 03, 2019 in Angular

Implementing routing in angular 4 with example

In this article, we will learn about step by step clearly implementing routing in angular 4 with example

learning topic

  • Introduction
  • Configuring and Navigating
  • Parameterized routes

Introduction routing in Angular

Angular provides ‘@angular/router’ library to enable routing in our application. Routing is used to navigate from one view to another when the user performs any task.

The angular router provides us to pass optional parameters along to the corresponding component to display the specific content.

We can bind a router to the links that will navigate us to the corresponding view when the user clicks.

<base href>:

  • This is one of the most is the most important thing in angular application to use routing.
  • This will be the first tag in <head> for most of the applications.
  • If the app folder is the application root the href should be as follows for non-CLI
<base href="/src/">
  • If app folder is not the application root, then we need to take the href from the document location as follows.
<script>document.write('<base href="' + document.location + '" />');</script>

Router Links:

The routerLink attribute is mostly used either on <a> or <button> tags which gives the router control over the element.  And routerLinkActive attributes will select the route as the default route.

<a routerLink="first-route" routerLinkActive="active">first route</a>
<button class="btn btn-primary" routerLink="first-route" routerLinkActive="active">first route</button>

Router Outlet:

This directive displays the inner content of the corresponding route component template in the current view.

<router-outlet></router-outlet>

Router Module:

This is an angular NgModule that provides the necessary services and directives which helps us to navigate between views.

import { Routes, RouterModule } from '@angular/router';
import { ModuleWithProviders } from '@angular/core';
const routes: Routes = [        
    { path: 'first-route', component: FirstComponent },
];
export const routing: ModuleWithProviders = RouterModule.forRoot(routes);

There are two ways to register our routes:

RouterModule.forRoot:forRoot creates a module that contains all the directives, the given routes, and the router service itself.

RouterModule.forChild: forChild creates a module that contains all the directives and the given routes, but does not include the router service.

Let us see a few more keywords that are useful for routing.

Router Part Meaning
Router Displays the application component for the active URL. Manages navigation from one component to the next.
RouterModule A separate Angular module that provides the necessary service providers and directives for navigating through application views.
Routes Defines an array of Routes, each mapping a URL path to a component.
Route Defines how the router should navigate to a component based on a URL pattern. Most routes consist of a path and a component type.
RouterOutlet The directive (<router-outlet>) that marks where the router displays a view.
RouterLink The directive for binding a clickable HTML element to a route. Clicking an element with a routerLink directive that is bound to a string or link parameters arraytriggers navigation.
RouterLinkActive The directive for adding/removing classes from an HTML element when an associated routerLink contained on or inside the element becomes active/inactive.
ActivatedRoute A service that is provided to each route component that contains route-specific information such as route parameters, static data, resolve data, global query params, and the global fragment.
RouterState The current state of the router including a tree of the currently activated routes together with convenience methods for traversing the route tree.
Link parameters array An array that the router interprets as a routing instruction. You can bind that array to a RouterLink or pass the array as an argument to the Router.navigate method.
Routing component An Angular component with a RouterOutlet that displays views based on router navigations.

Configuring  and Navigating

Now let us create an application. Create the following files as shown in the below pic

Implementing routing in angular 4 with example
Implementing routing in angular 4 with example

Step1: Creating models

Let us create models that are required for our application

File: app.models.ts

export class Department {
    DeptId: number;
    DeptName: string;
}
export class Employee {
    EmpId: number;
    EmpName: string;
    EmpSalary: number;
    Department: Department;
}

Step2: Create the components required

First, let us create child components EmpComponent and DeptComponent

File: app.EmpComponent.ts

import { Component} from '@angular/core';
import { Employee } from './app.models';

@Component({
    templateUrl: './emptemplate.html'
})
export class EmpComponent{
    emps: Employee[];
    constructor() {
        var lstEmp: Employee[] = [
            { EmpId: 1, EmpName: "Phani", EmpSalary: 15000, Department: { DeptId: 1, DeptName: "D1" } },
            { EmpId: 2, EmpName: "Kranth", EmpSalary: 115000, Department: { DeptId: 2, DeptName: "D2" } }
        ];
        this.emps = lstEmp;
        }
}

In this application I’ve created few static employees, if we want to make them dynamic we need to use HTTP services and fetch the data from the server, we will discuss how to fetch data from the server in the services session.

File: emptemplate.html

<table class="table table-bordered">
    <tr>
        <th>Name</th>
        <th>Department</th>
    </tr>
    <tbody>
        <tr *ngFor="let emp of emps">
            <td>{{emp.EmpName}}</td>
            <td>{{emp.Department.DeptName}}</td>
         </tr>
    </tbody>
</table>

Now create DeptComponent

File: app.DeptComponent.ts

import { Component} from '@angular/core';
import { Department } from './app.models';

@Component({
    templateUrl:'./depttemplate.html'
})
export class DeptComponent{
    depts: Department[];
        constructor() {
        var lstDept: Department[] = [
            { DeptId: 1, DeptName: "D1" },
            { DeptId: 2, DeptName: "D2" }
        ];
        this.depts = lstDept;
    }
}

File: depttemplate.html

<table class="table table-bordered">
    <tr>
        <th>Name</th>
    </tr>
    <tbody>
        <tr *ngFor="let dept of depts">
            <td>{{dept.DeptName}}</td>
         </tr>
    </tbody>
</table>

Now let’s create root component

File: app.component.ts

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

@Component({
    selector: 'my-app',
    templateUrl: './template.html'
})
export class AppComponent { 
constructor(private router:Router) { }
gohome() {
        this.router.navigate(['emp']);
    }
}

Here instead of using automatic routing, we can use manual routing using Router.Navigate.

File: template.html

<div class="container">
    <h1>Office Management</h1>
    <nav>
        <button class="btn btn-warning" routerLink="emp">Employees</button>
        <button class="btn btn-warning" routerLink="dept">Departments</button>
    </nav>
    <br />
    <router-outlet></router-outlet>
</div>

Step3: Create routing required

File: app.routings.ts

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { EmpComponent } from './app.EmpComponent';
import { DeptComponent } from './app.DeptComponent';

const routes: Routes = [        
    { path: '', redirectTo: 'emp', pathMatch: 'full' },
    { path: 'emp', component: EmpComponent },
    { path: 'dept', component: DeptComponent },
 ];
export const routing: ModuleWithProviders = RouterModule.forRoot(routes);

Step4: Setup NgModule & bootstrap the application

File: app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent} from './app.component';
import { routing } from './app.routings';
import { EmpComponent } from './app.EmpComponent';
import { DeptComponent } from './app.DeptComponent';

@NgModule({
    imports: [BrowserModule, routing],
    declarations: [AppComponent, EmpComponent, DeptComponent],
  bootstrap: [AppComponent]
})
export class AppModule {  }

File: main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);

File: src/RoutingExample.html

<!DOCTYPE html>
<html>
<head>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 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/systemjs/dist/system.src.js"></script>
    <script src="systemjs.config.js"></script>
    <link href="/Content/bootstrap.css" rel="stylesheet" />
    <script src="/Scripts/jquery-1.10.2.js"></script>
    <script src="/Scripts/bootstrap.js"></script>
    <script>
        System.import('app/Routing/main.js').catch(function (err) { console.error(err); });
    </script>
</head>
<body>
    <my-app>Loading...</my-app>
</body>
</html>

Output: Here if you click on Go Home it will redirect you to Employees by using manual routing.

implementing Configuring and Navigating in angular

Parameterized routes

From the above example if we want to get the details of individual record of any Employee then we have to show the URL as Emp/1 Emp/2 . . . .

To achieve this we need to create one more route to accept the parameters.

File: app.routings.ts

const routes: Routes = [        
    { path: '', redirectTo: 'emp', pathMatch: 'full' },
    { path: 'emp', component: EmpComponent },
    { path: 'emp/:id', component: EmpComponent },
    { path: 'dept', component: DeptComponent },
    { path: 'dept/:id', component: DeptComponent }
];

Now to accept the parameters in the target component we need to import ActivatedRoute

import { ActivatedRoute } from '@angular/router';

Target component fires when the user clicks on a link/button, then we need to fetch the parameter using ActivatedRoute

File: app.EmpComponent.ts

Modify the constructor as follows

constructor(private route: ActivatedRoute) {
        var lstEmp: Employee[] = [
            { EmpId: 1, EmpName: "Phani", EmpSalary: 15000, Department: { DeptId: 1, DeptName: "D1" } },
            { EmpId: 2, EmpName: "Kranth", EmpSalary: 115000, Department: { DeptId: 2, DeptName: "D2" } }
        ];
        this.emps = lstEmp;
        this.route.params.subscribe(params => console.log(params));
    }

This gives the output as follows in console { id : 2 } Using its key we can fetch the value of the parameter.

this.route.params.subscribe(params => this.getEmp(params["id"]));

Now below constructor create a method

getEmp(id: any) {
        if (id !== undefined)
           this.filteredemp = this.emps.filter(e => e.EmpId == id);
    }

Now this is how your EmpComponent looks like

export class EmpComponent{
    constructor(private route: ActivatedRoute) {
        var lstEmp: Employee[] = [
            { EmpId: 1, EmpName: "Phani", EmpSalary: 15000, Department: { DeptId: 1, DeptName: "D1" } },
            { EmpId: 2, EmpName: "Kranth", EmpSalary: 115000, Department: { DeptId: 2, DeptName: "D2" } }
        ];
        this.emps = lstEmp;
        this.route.params.subscribe(params => this.getEmp(params["id"]));
    }
    emps: Employee[];
    filteredemp: Employee[];
   
    getEmp(id: any) {
        if (id !== undefined)
           this.filteredemp = this.emps.filter(e => e.EmpId == id);
    }
}

File: emptemplate.html

Add one more column in the table as follows

<table class="table table-bordered" style="width:50%">
    <tr>
        <th>Name</th>
        <th>Department</th>
        <th></th>
    </tr>
    <tbody>
        <tr *ngFor="let emp of emps">
            <td>{{emp.EmpName}}</td>
            <td>{{emp.Department.DeptName}}</td>
            <td><a [routerLink]="['/emp',emp.EmpId]">Details</a></td>
        </tr>
    </tbody>
</table>

To display the filtered result add the following code

<div *ngIf="filteredemp?.length >0">
    <h3>Details</h3>
    <ul *ngFor="let emp of filteredemp">
        <li>EmpName: <b>{{emp.EmpName}}</b></li>
        <li>EmpSalary: <b>{{emp.EmpSalary}}</b></li>
        <li>Department: <b>{{emp.Department.DeptName}}</b></li>
    </ul>
</div>

Output: Click on the Details link will show the details of the corresponding

Parameterized routes
Parameterized routes

Summary

In this article, we will learned Implementing routing in angular 4 with example the next article we will learn different types of routing in angular 4 with examples clearly

Like
Like Love Haha Wow Sad Angry
2

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x