Angular 5 is the latest framework for building web applications using typescript. Recently, angular team is skipped the version 3.x because, router package is shipped with 3.x previously, so instead of putting into 3.x, choose to move to 4.x. Current latest version is 5

Sunday, 13 November 2016

Angular 2 Routing

Angular Router is not a part of Angular core. it has its own library package @angular/router.

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

There are three main components used for configuring routing in Angular 2.
  • RouteConfig – It describes the application routes
  • RouterOutlet –It is a placeholder for each route content.
  • RouterLink – It provide the link to the routes.

It also allows for Child routes, lazy loading of the data, Auxiliary Routes.


The app contains one router. When the url changes, it looks for corresponding Route.

To install router into the application, we have to use ‘RouterModule.forRoot() function in the imports key of the NgModule.
We bootstrap the application with array of routes.
   imports: [
declarations: [ AppComponent, MyComponent, MainComponent ], providers : [appRoutingProviders], bootstrap : [AppComponent] }) export class MyAppModule { }

You can write some routing configuration, map certain url paths to angular components.
RouteConfig is an array of 'Route' configuration object.


It is used to define the routes.
path : ‘/firstComponent’,
as : ‘FirstComponent’,
useAsDefault : true,
component: FirstComponent
path : ‘/secondComponent’,
as : ‘SecondComponent’,
useAsDefault : true,
component: SecondComponent
path : ‘/thirdComponent’,
as : ‘ThirdComponent’,
useAsDefault : true,
component: ThirdComponent    }
export class BasicRouting {}
use path to specify the url.
Specify the component that we want to route to
redirectTo option for redirect

if you navigate to /firstComponent then the FirstComponent will displayed.
if you navigate to /secondComponent then the SecondComponent will displayed.
 Once url match, it will display the matching components and for that , it look in the template for router-outlet component.

RouterOutlet :

It is a placeholder component which is similar to the view that renders the content of the each route.


  template: `
    Basic Routing

Whenever the route changes, the content will be rendered in the place of router-outlet tag.
For example, if we switch to /home page, the content rendered by HomeComponent would be placed here.

RouterLink :

It is used to link the different routes within the application. We use router-link here which is similar to ui-sref directive in angular 1.x
        <li><a [router-link]="['firstpage']">First Page</a></li>
        <li><a [router-link]="['secondpage']">Second Page </a></li>
        <li><a [router-link]="['thirdpage']">Third Page</a></li>


0 coment�rios:

Post a Comment


Online Training

Your Name :
Your Email: (required)
Your Message: (required)

Powered by Blogger.

Recent Posts

Find Us On Facebook

Popular Posts