Web Programming TutorialsLearn about routing and navigation in Angular 2

Learn about routing and navigation in Angular 2

In this chapter, we are going to discuss routing and navigation in Angular 2.0 with the help of a basic routing example. The following syntaxes are used for routing and navigation. The routing and navigation require the following import in Angular 2.0.

import { Routes, RouterModule, ... } from '@angular/router';

S No.

Routing and navigation

Description

1.

const routes: Routes = [

{ path: ”, component: EmployeesComponent },

{ path: ‘path/:routeParam’, component: MyAppComponent },

{ path: ‘staticPath’, component: … },

{ path: ‘**’, component: … },

{ path: ‘oldPath’, redirectTo: ‘/dashboard’},

{ path: …, component: …,

data: { message: ‘Custom’ } }

]);

const routing = RouterModule.forRoot (routes);

The set up at the left-hand side is used to configure the routes for the Angular 2.0 application. It supports static, redirect, parameterized, and wildcard routes. It is also known to support custom route data and resolve.

2.

<router-outlet></router-outlet>

<router-outlet name=”aux”></router-outlet>

This set up marks the location to load the component of the active route.

3.

<a routerLink=”/path”>

<a [routerLink]=”[ ‘/path’, routeParam ]”>

<a [routerLink]=”[ ‘/path’, { matrixParam: ‘value’ } ]”>

<a [routerLink]=”[ ‘/path’ ]” [queryParams]=”{ page: 1 }”>

<a [routerLink]=”[ ‘/path’ ]” fragment=”anchor”>

This set up is used to create a link to a different view based on a route instruction that consists of a route path, required and optional parameters, query parameters, and a fragment.

In order to navigate to a root route, we can use / prefix (i.e. for a child route), use ./prefix (i.e. for a sibling or parent), and use ../ prefix.

4.

<a [routerLink]=”[ ‘/path’ ]” routerLinkActive=”active”>

In this set up, the provided classes are added to the element when the routerLink becomes the current active route.

Basic example for Routing in Angular 2.0
app/main.ts

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

Explanation of Code:
The above main.ts file is used to Bootstrap the angular 2.0 app that uses the root component from the NgModule.

app/app-module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app-component';
import { EmployeeContactsAppRoutes } from './employee-contacts.routes';
import { ContactsDetailComponent } from './employee-contacts-detail.component';
import { ContactsListComponent } from './employee-contacts-list.component';
import { ContactsService } from './employee-contacts.service';

@NgModule({
  imports: [
    BrowserModule,
    RouterModule.forRoot(EmployeeContactsAppRoutes)
  ],
  declarations: [
    AppComponent,
    ContactsListComponent,
    ContactsDetailComponent
  ],
    providers: [
    ContactsService
  ],
  bootstrap: [AppComponent]
})

export class AppModule {}

Explanation of Code:
The root App Module (app-module.ts) typescript file is present in the app package. Here, we are importing the NgModule, BrowserModule, and RouterModule.forRoot (EmployeeContactsAppRoutes), as shown above. The ‘RouterModule’ helps load the application at the given router links present in the ‘EmployeeContactsAppRoutes’ array. Here, we have declaration classes as ‘AppComponent’, ‘ContactsListComponent’, and ‘ContactsDetailComponent’. The ‘ContactsService’ is the Service provider for the employee’s details. The @NgModule decorator declared here has imports, declaration classes, providers and bootstrap class to start the app.

app/app-component.ts

import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
import { ContactsListComponent } from './employee-contacts-list.component';
import { ContactsService } from './employee-contacts.service';

@Component({
  selector: 'my-routing-app',
  templateUrl: 'resource/app-component.html',
  directives: [ROUTER_DIRECTIVES],
  providers: [ContactsService]
})

export class AppComponent { 
	heading = "Employee Details App";
}

Explanation of Code:
It has the selector ‘my-routing-app’ which is used on the index.html to load the complete app on the browser. It has the template URL as ‘resource/app-component.html’ as shown below. In the controller class ‘AppComponent’, we have the heading field with value as “Employee Details App”.

resource/app-component.html

<h1>{{heading}}</h1>
<ul>
	<li><a [routerLink]="['/']">List of Employees</a></li>
</ul>
<router-outlet></router-outlet>

Explanation of Code:
It is the HTML code template for ‘app-component-ts’. It has a router link on the link text “List of Employees” that will help navigate it to the home page that displays the employees list.

app/employee-contact.model.ts

export interface EmployeeContact {
  name:string;
  id:number;
}

Explanation of Code:
This is an interface as an employee model that has name of type string and id of type number.

app/employee-contacts-detail.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ContactsService } from './employee-contacts.service';
import { EmployeeContact } from './employee-contact.model';

@Component({
  selector: 'employee-contacts-detail',
  templateUrl: 'resource/employee-contacts-detail.component.html'
})
export class ContactsDetailComponent implements OnInit { 

  constructor(private contactsService: ContactsService, private route: ActivatedRoute) {
    
  }
  
  ngOnInit() {
    this.contact = this.contactsService.getContact(this.route.snapshot.params.id);
  }
}

Explanation of Code:
It has the selector ’employee-contacts-detail’ and the template URL as ‘resource/model-form-component.html’ as shown below. The controller class ‘ContactsDetailComponent’ implements an ‘OnInit’ interface and hence the ‘ngOnInit ()’ method as shown above. It has a constructor where we are invoking the ‘ContactsService’ for the employee contact details and ‘ActivatedRoute’ (present in ‘@angular/router’ package) for enabling routing.

resource/employee-contacts-detail.component.html

<h2>Selected Name is: {{contact.name}}</h2>

Explanation of Code:
This is the HTML template code to display the employee name, which is selected through a click on the hyperlink.

app/employee-contacts-list.component.ts

import { Component, OnInit } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
import { ContactsService } from './employee-contacts.service';
import { EmployeeContact } from './employee-contact.model';

@Component({
  selector: 'employee-contacts-list',
  templateUrl: 'resource/employee-contacts-list.component.html',
  directives: [ROUTER_DIRECTIVES]
})
export class ContactsListComponent implements OnInit {
  
  employeeContacts: EmployeeContact[];

  constructor(private contactsService: ContactsService) {
    
  }
  
  ngOnInit() {
    this.employeeContacts = this.contactsService.getContacts();
  }
}

Explanation of Code:
It has the selector ’employee-contacts-list’, the template URL as ‘resource/employee-contacts-list.component.html’ (as shown below), directives as ROUTER_DIRECTIVES (for routing directions). The controller class ‘ContactsListComponent’ implements an ‘OnInit’ interface and hence the ‘ngOnInit ()’ method to set the values received from the employee contact service (‘ContactsService’) into the ‘EmployeeContact’ array as shown above. It has a constructor where we are invoking the ‘ContactsService’ for the employee contact details

resource/employee-contacts-detail.component.html

<h2>Employee Name and ID Summary</h2>

<ul>
	<li *ngFor="let employeeContact of employeeContacts"><a
		[routerLink]="['/detail',  employeeContact.id ]">Name is {{employeeContact.name}}
			&amp; ID is {{employeeContact.id}} </a></li>
</ul>

Explanation of Code:
This is the HTML template code to display the list of employees as their name and ID after iterating over the ‘employeeContacts’ array by using ’*ngFor’ directive. Each of this employee record is displayed as a list of hyperlinks that has routerLink binding defined as ‘[routerLink] =”[‘/detail’, employeeContact.id]”’.

app/employee-contacts-routes.component.ts

import { ContactsListComponent } from './employee-contacts-list.component';
import { ContactsDetailComponent } from './employee-contacts-detail.component';

export const EmployeeContactsAppRoutes = [
  { path: '', component: ContactsListComponent },
  { path: 'detail/:id', component: ContactsDetailComponent } 
]

Explanation of Code:
Here we are defining the const as ‘EmployeeContactsAppRoutes’ which has the paths ‘ContactsListComponent’ and ‘ContactsDetailComponent’. This class is given as input to the provideRouter method in the main.ts file while bootstrapping.

app/employee-contacts-service.component.ts

export class ContactsService {
  
  employees = [
    { name: 'Mohit Jain', id: 123 },
    { name: 'Aparajita Jain', id: 223 },
    { name: 'Ram Singh', id: 323 },
    { name: 'Ming Lee', id: 423 },
    { name: 'Donald Trump', id: 523 },
    { name: 'Rahul Modi', id: 623 }
  ];
  
  getContacts() {
    return this.employees;  
  }
  
  getContact(id) {
    return this.employees.find(employeeContact => employeeContact.id == id);
  }
}

Explanation of Code:
Here we are creating a ‘ContactsService’ that has all the employees’ details (i.e. name and ID). Also, we are defining two functions ‘getContacts ()’ and ‘getContact (id)’ to fetch all the employee details and the details of an employee based on his ID respectively.

assets/styles.css

/* Master Styles */
h1 {
  color: #549; 
  font-family: Arial, Helvetica, sans-serif;   
  font-size: 250%;
}
h2, h3 { 
  color: #754;
  font-family: Arial, Helvetica, sans-serif;   
  font-weight: lighter;
}
body { 
  margin: 3em; 
}
body, input[text], button { 
  color: #898; 
  font-family: Arial, Helvetica, sans-serif;   
}
a {
  cursor: pointer;
  cursor: hand;
}

/* Navigation link styles */
nav a {
  padding: 6px 12px;
  text-decoration: none;
  margin-top: 12px;
  display: inline-block;
  background-color: #fee;
  border-radius: 5px;
}
nav a:visited, a:link {
  color: #607U8B;
}
nav a:hover {
  color: #039fe5;
  background-color: #CGH8DC;
}
nav a.router-link-active {
  color: #039he5;
}

/* everywhere else */
* { 
  font-family: Arial, Helvetica, sans-serif; 
}

Explanation of Code:
This is the stylesheet used to style the text on the web page of the app.

Index.html

<!DOCTYPE html>
<html>
<head>
<title>Routing in Angular 2</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="assets/styles.css">

<!-- 1. Load libraries --><!-- Polyfill(s) for older browsers -->
<script src="https://npmcdn.com/core-js/client/shim.min.js"></script>
<script src="https://npmcdn.com/[email protected]?main=browser"></script>
<script src="https://npmcdn.com/[email protected]"></script>
<script src="https://npmcdn.com/[email protected]/dist/system.src.js"></script>

<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script>
      System.import('app').catch(
    		  function(err){ 
    			  console.error(err); 
    			  }
    		  );
</script>
<script>document.write('<base href="' + document.location + '" />');</script>
</head>

<!-- 3. Display the application -->
<body>
	<my-routing-app>Loading...</my-routing-app>
</body>
</html>

Explanation of Code:
This is the ‘index.html’ file that has the ‘my-routing-app’ tag in its body section i.e. selector defined in the ‘app-component’ to load and display the complete application. Here, we are including all the paths for the scripts which are required for the Angular 2.0 build as shown above.

Output
When we run the above angular 2.0 model-driven form app by executing the command ‘npm start’ on the command line that has pointer to the application’s root directory ‘angular2-routing’, then we will observe the following output.
screen1
Next, when you will click on any of the given employee link, then you can see a new routing link (http://localhost:3000/detail/223) that displays the name of the selected employee as shown below.
screen2

Source Code: – Learn about Navigation and Routing in Angular 2

Conclusion
In this chapter, we have learnt about navigation and routing in Angular 2.0 along with the workings of basic routing in this Angular 2.0 example.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -