5/25/16

Routes In Angular2 (Part 2)

In previous post we talked about routes in angular2. We saw some basic example of app using routes. But what about nested routes?

Nested Routes

Lets say for example that we need in our application to have a login page which has no menus on it. After passing authentication user should be redirected to protected pages which have the same menus on each of them:

Step 1

Transfer application to use nested routes is very easy.
First you need to create the middle ware route which will host its own routes directive on it. Lets call it layout.
On this middle ware view we will locate the menu.

import {Component} from 'angular2/core'
import {RouteConfig, Router, Route,  ROUTER_DIRECTIVES} from 'angular2/router';
...
@Component({
  selector: 'layout',
 template: `
    <h2>Hello {{name}}</h2>
    <!-- menu is located here now -->
    <a [routerLink]="['Layout']">Dashboard</a> | 
    <a [routerLink]="['Reports']">Reports</a> |
    <a [routerLink]="['Login']">Login</a>
    <hr>
   <!-- router directive -->
   <router-outlet></router-outlet>, 
 directives: [ROUTER_DIRECTIVES]
})

  
@RouteConfig([
   new Route({path: '/', name: 'Dashboard', component: Dashboard, useAsDefault:true}),
   new Route({path: '/reports', name: 'Reports', component: Reports})
])
export class Layout {
  constructor(){
    this.name = 'Angular2 Nested Routes';
  }
}

Step 2

Next thing lets create the login page which will located at the base root route "/login".

import {Component} from 'angular2/core'

@Component({
  selector: 'login',
 template: `
   <div>
     <h1>Please Log In</h1>
     <div style="text-align:center">
           username:<input> 
     </div>
     <div style="text-align:center">
           password:<input> 
     </div>
     <div style="text-align:center">
      <button (click)="login()">login</button>
    </div>
   </div>  `
})

export class Login {
  constructor(public router: Router){}
  login(){
    this.router.navigate(['Layout']);
  }
}


Also lets create the Dashboard page which will located at the inner route "layout/dashboard".

Step 3

Last thing we should modify the root "app" component so it will support nested routes:

import {Component} from 'angular2/core'
import {RouteConfig, Router, Route,  ROUTER_DIRECTIVES} from 'angular2/router';
import {Layout} from './layout';
import {Login} from './login';


@Component({
  selector: 'my-app',
  template: `
      <router-outlet></router-outlet>
  `,
  directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
   new Route({path: '/layout/...', name: 'Layout', component: Layout}),
   new Route({path: '/login', name: 'Login', component: Login}),
   {
    path: '/**',
    redirectTo: ['Layout']
  }
])
export class App {
}

Here is running code: Hope you have fun reading...

No comments:

Post a Comment

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...