Location Strategy- Routing in Angular2

Angular 2’s router is super easy to use. Angular 2 gives you the possibility of dividing your application into several views that you can navigate between through the concept of routing. Routing enables you to route the user to different components based on the url that they type on the browser, or that you direct them to through a link. This post will cover standard routing, route parameters and nested child routes in Angular2. With these basics we can build a great navigation experience for users.

Configuration and Declaring Routes

A routed Angular application has one singleton instance of the Router service. When the browser’s URL changes, that router looks for a corresponding Route from which it can determine the component to display.

A router has no routes until you configure it. The following example creates four route definitions, configures the router via the RouterModule.forRoot method, and adds the result to the AppModule‘s imports array.

The first thing that we need to do when setting up routes for any project is to define the routing table. We will start out with a basic home route that maps to the HomeComponent and then add another route to redirect the root path to our home route.

const homeRoutes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'service', component: ServiceComponent }

Our route config defines all the routes in our application. The first route is our default home route. The second one is our serviceComponent. The path value is the path that we referenced in our template. We export our routes to be added to our App Module.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';

import { routes } from './app.routes';
import { AppComponent } from './app.component';
import { ServiceComponent } from './about.component';
import { HomeComponent } from './home.component';

 imports: [
 declarations: [
 bootstrap: [ AppComponent ]
export class AppModule {

The appRoutes array of routes describes how to navigate. Pass it to the RouterModule.forRoot method in the module imports to configure the router.

Router outlet

Router outlet Acts as a placeholder that Angular dynamically fills based on the current router state. Given this configuration, when the browser URL for this application becomes /home, the router matches that URL to the route path /home and displays the HomeComponent after a RouterOutlet that you’ve placed in the host view’s HTML.

<!-- Routed views go here -->

Each Route maps a URL path to a component. There are no leading slashes in the path. The router parses and builds the final URL for you, allowing you to use both relative and absolute paths when navigating between application views.

Nested Child Routes

So we have the following routes, / and /service. 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 /service and /service/item. The first route would be the default about page but the more route would offer another view with more details.

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.

Service view has its own router-outlet highlighted in blue. The about view also has its own links that navigate between two nested about child components.

So ourservice components will look like

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

 selector: 'home',
 template: `<h3>About Home</h3>`
export class AboutHomeComponent { }

 selector: 'about-item',
 template: `<h3>About Service Item</h3>`
export class AboutServiceItemComponent { }

 selector: 'app-about',
 template: `
 <a [routerLink]="['/about']">Home</a>
 <a [routerLink]="['/about/item']">Service Item</a>
` }) export class AboutServiceComponent { }

So ourAboutService template looks very similar to the App component template. Our about component has two child routes, /about and about/item These pull in two simple components that just display the rendered text above. Notice our route paths start at the root of the about component. The rendered URLs would be /about/ and /about/item. Note remember to add our newly created components to the declarations in our AppModule. After thatour route config will be updated to:

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

import { AboutServiceComponent, AboutServiceItemComponent, AboutHomeComponent } from 'app/about.component';
import { HomeComponent } from 'app/home.component';

export const routes: Routes = [
 { path: '', component: HomeComponent }
 path: 'about',
 component: AboutComponent,
 children: [
 { path: '', component: AboutHomeComponent }, // url: about/
 { path: 'item', component: AboutItemComponent } // url: about/item

Now we will see how to dynamically change data in our component via route parameters.

Route definition with a parameter

Route parameters allow us to pass values in our url to our component so we can dynamically change our view content. So in our example we will have a route that can take an id and then display it on our AboutServiceItemComponent component.

Our URLs would be the following: /about/, /about/item/1, and /about/item/2. We can swap out any number in our URL and our item component can pull that value out and display it in the view. Let’s take a look at the code for the root about component.

    selector: 'app-about',
    template: `
      <a [routerLink]="['/about']">Home</a>
      <a [routerLink]="['/about/item', 1]">Item 1</a>
      <a [routerLink]="['/about/item', 2]">Item 2</a>
      <div class="inner-outlet">
export class AboutServiceComponent { }

The :id in the second route is a token for a route parameter. In a URL such as about/item/2, “2” is the value of the id parameter. The corresponding AboutServiceComponent will use that value to find and present the Item whose id is 2.

the : denotes that this is a route parameter and the r outer should get the value in the URL. So now lets take a look at the AboutServiceItemComponent and see how we can get the id from the URL.

We import the ActivatedRoute class and inject it into our component. The parameters are wrapped in an Observable that will push the current route parameter value whenever the parameter is updated. We subscribe for any changes. When a new value is received we set the value to a property on our template. We could just as easily taken this value as an ID to retrieve some data from a API. We capture the subscription in a property so when the component is destroyed we unsubscribe preventing any memory leaks.

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

 selector: 'about-item',
 template: `<h3>About Item Id: {{id}}</h3>`
export class AboutServiceItemComponent { 
 id: any;
 paramsSub: any;
 constructor(private activatedRoute: ActivatedRoute) { }
 ngOnInit() {
 this.paramsSub = this.activatedRoute.params.subscribe(params => this.id = parseInt(params['id'], 10));
 ngOnDestroy() {

Using Observables to get route params works well when the component persists on the same screen without having to be destroyed and recreated each time.

Excerpt from : https://coryrylan.com/blog/introduction-to-angular-routing


About AshuTomar

Ashu is a Software Consultant at Knoldus Software LLP. she has good knowledge of HTML5, CSS3, java script, less, sass bootstarp framework. She is flexible, adaptive and self motivated personality. She have strong analytical and problem solving skills. She is highly passionate to learn and explore new technologies.
This entry was posted in Angular Material, AngularJS, AngularJs2.0, Scala and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s