Angular 2 Router Example

 

Angular 2 Router is the library used to manage the navigation inside an Angular 2 application.

angular 2 router
angular 2 router

Angular 2 applications are composed from a number of Views. Your visitors normally navigate from one view to another. And this is the mission of Angular 2 Router.

angular 2 router live example
angular 2 router live example

 

try it angular 2 router
try angular 2 router
/**
 * Created by Tareq Boulakjar. from angulartypescript.com
 */
import {Component} from 'angular2/core';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {ContactComponent} from "./contact.component";
import {ProductsComponent} from "./products.component";
import {AboutUsComponent} from "./about-us.component";
import {ProductDetailComponent} from "./product-detail.component";
import {CarService} from "./car.service";
import {ConfirmDialogService} from "./confirm-dialog.service";


@Component({
    selector: 'my-app',
    template: `
    <h3 class="title">Angular 2 Router Example</h3>
    <nav>
      <a [routerLink]="['Products']">Products</a>
      <a [routerLink]="['AboutUs']">About Us</a>
      <a [routerLink]="['Contact']">Contact</a>
    </nav>
    <router-outlet></router-outlet>
  `,
    providers:  [ConfirmDialogService,CarService],
    directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([

    {
        path: '/contact',
        name: 'Contact',
        component: ContactComponent,
        useAsDefault: true
    },

    {
        path: '/products',
        name: 'Products',
        component: ProductsComponent
    },
    {
        path: '/about-us',
        name: 'AboutUs',
        component: AboutUsComponent
    },
    {path: '/car/:id', name: 'CarDetail', component: ProductDetailComponent},
])
export class RouteExampleAppComponent { }
/* Copyright 2016 angulartypescript.com. All Rights Reserved. Everyone can use this source code; don’t forget to indicate the source please: http://www.angulartypescript.com/ */ 

 

  • In this chapter we will cover all the functionalities offered by Angular 2 router (step by step):
step 1 - include router library and href configure
step 1 – include router library and href configure

 

  • We load the router library (in index.html)

<script src=”PATH/router.dev.js“></script>

  • We set base href (in index.html)

<script>document.write(‘<base href=”‘ + document.location + ‘” />’);</script>

angular 2 rout main component
angular 2 rout main component
  • We configure a Router (e.g. in our main component: file : app.component.ts)
  1. A router contains a list of routes (or paths) definitions.
  2. As you already know a router allows us to navigate between views, right?
  3. Yes, and in our example we want to navigate from the main app (app.component.ts)
  4. _ We export this component with the class name RouteExampleAppComponent.
  5. _ In this case RouteExampleAppComponent considered as a Host Component  angular-2-effortless
  6. Host Component is the Entry of all navigations.
  7. To configure your router use the @RouteConfig() decorator.

let’s see all that in our code :


@RouteConfig([

{
path: '/contact',
name: 'Contact',
component: ContactComponent,
useAsDefault: true
},

{
path: '/products',
name: 'Products',
component: ProductsComponent
},
{
path: '/about-us',
name: 'AboutUs',
component: AboutUsComponent
},
{path: '/car/:id', name: 'CarDetail', component: ProductDetailComponent},
])

@RouteConfig() accepts as parameter an array of route definitions.

angular 2 router definitions
angular 2 router definitions
  • In our example we have 4 definitions.
definitions names : Contact,Products,AboutUs and CarDetail
  • A definition has 3 parameters:

path : is what we  see in the browser’s Address bar   (e.g /contact)

name : the name used internally by the application (e.g Contact)

component : is the component called when we access this route.

angular 2 router - routerLink directive
angular 2 router – routerLink directive

 

  • You noticed that we use [routerLink] directive.

<a [routerLink]=”[‘Products’]”>Products</a>

  1. “[‘Products’]” : This is called Link Parameters Array (in this case with one element).
  2. ‘Products’:is a route.
  • Link Parameters Array within a method: (we will use it later)
  1. this._router.navigate( [‘CarDetail’, { id: car.id }] );
  2. ‘CarDetail’: is a route.

 

angular 2 router - router-outlet
angular 2 router – router-outlet

 

  • When we access a route, we tell Angular Router to create the associated component and draw its view. Inside the

<router-outlet></router-outlet>

  •  When you navigate in angular 2 application using the router, your navigation is stored in browser’s history, so you can use the back and forward buttons in your browser.

 

router - navigation n level
router – navigation n level

 

  • Until now we can navigate from one view to another (Products, Contact, and About Us)

 

  •  Now we want to add view Detail to our Products (cars) elements. (Click to see Car detail)

 

add navigation to ul list
add navigation to ul list

 

in our products component (file: produts.component.ts) we add a click event to our ul list, to allow the user to view the detail of a car.

  • In our list (ul) we add for each (li) a click event to go into Detail View

<li (click)=”onSelectCar(car)”>

We pass the current car as parameter (we need this parameter to view the detail in Detail component)

 

Show detail of requested car
Show detail of requested car

 

We have clicked a link in the component above, and now we are in another component called product detail component (file: product-detail.component.ts)

We get the requested car Id and we show its details.


<h3>Angular 2 - Car Detail</h3>
<div *ngIf="car">
<h3>"{{car.name}}"</h3>
<div>
<label>Car Id: </label>{{car.id}}</div>
<div>
<label>Car Name: </label>
<input [(ngModel)]="carNameEdit" placeholder="name"/>
</div>
<button (click)="backToProductsList()">Back</button>
</div>

 

route parameters
route parameters

 

  • What are route parameters? (file: products.component.ts)

To view the car Detail we need to know its id. We send the id with the navigation as a second parameter. { id: car.id }

example the id sent in a URL : URL/car/1

This will allow us to show the view related to the car with the id 1.


onSelectCar(car) {

this._router.navigate( ['CarDetail', { id: car.id }] );

}

 

angular 2 router - default view
angular 2 router – default view
  • Setting the default view to draw when access the application. (file : angular-2-router.ts)
  1. useAsDefault: true

{

path: '/contact',

name: 'Contact',

component: ContactComponent,

useAsDefault: true

},

 

angular 2 router Lifecycle
angular 2 router Lifecycle

 

  • As we have already seen in a previous chapter, Angular 2 manages the Lifecycle of a component. And it uses some methods to access the key moment during the component life.
  1. The router library has more lifecycle methods.
  • routerCanActivate : Check if a component can be instantiated.
  •  routerCanDeactivate : Check if a component can be removed.

2. When the user modifies the name of a car and he clicks to leave the current view he will get a message from this method:

this._dialog.confirm(‘Ignore changes (are you sure you want to leave this window) ?’);

angular 2 router confirm dialog
angular 2 router confirm dialog
angular 2 router - query parameter
angular 2 router – query parameter

 

 

  • URL Query parameter (string) is used to transfer complex information between views during navigation.

Query parameter is declared the same way as we do with route parameters.

We choose Route parameter or Query parameters?

  1. Route parameter: if it’s required and if we want to distinguish a route parameter from others.
  2. Query parameter: it’s complex and or optional.

 

angular 2 router - html 5 or hash navigation
angular 2 router – html 5 or hash navigation

 

  • The router uses the “HTML 5  pushState” style by default, we must configure that strategy with a base href
  • if you want to use the # url format you can add this to main.ts file

bootstrap(AppComponent, [
ROUTER_PROVIDERS,
provide(LocationStrategy,
{useClass: HashLocationStrategy})
]);

  • Use # only if you have a strong reason.
  • It’s recommended: Angular 2 applications should use the HTML 5 navigation Style (no hash #). As a result we get easy and readable URL. And we will use it later in server-side rendering.
angular 2 router - ROUTER_PROVIDERS
angular 2 router – ROUTER_PROVIDERS

 

Don’t forget to add the provider to the bootstrap (file: main.ts)

bootstrap (AppComponent, [ROUTER_PROVIDERS]);

 

Done !