Show Menu
Cheatography

Angular 2 Router Cheat Sheet by

Ng2 Router

Getting started

In index.html

<base href="/">

Router Imports

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

Sample Router

RouterModule.forRoot([
      { path: 'hero/:id', component: HeroDetailComponent },
      { path: 'crisis-center', component: CrisisListComponent },
      {
        path: 'heroes',
        component: HeroListComponent,
        data: {
          title: 'Heroes List'
        }
      },
      { path: '', component: HomeComponent },
      { path: '**', component: PageNotFoundComponent }
    ])
  ]
There is an array of routes defined for the specific section of the applic­ation, depending on the embedded nature of the applic­ation there will be more child routes defined

General

1. The order of the routes matter
2. There is usually a default route with an empty path

Router Outlet

<!-- Routed views go here -->
<router-outlet></router-outlet>

Router Link

RouterLink
The directive for binding a clickable HTML element to a route. Clicking an anchor tag with a routerLink directive that is bound to a string or a Link Parameters Array triggers a naviga­tion.
Router­Lin­kActive
The directive for adding­/re­moving classes from an HTML element when an associated routerLink contained on or inside the element becomes active­/in­active.
Activa­ted­Route
A service that is provided to each route component that contains route specific inform­ation such as route parame­ters, static data, resolve data, global query params and the global fragment.
Router­State
The current state of the router including a tree of the currently activated routes in our applic­ation along conven­ience methods for traversing the route tree.
Router
Displays the applic­ation component for the active URL. Manages navigation from one component to the next.
Router­Module
A separate Angular module that provides the necessary service providers and directives for navigating through applic­ation views.
Routes
Defines an array of Routes, each mapping a URL path to a component.
Route
Defines how the router should navigate to a component based on a URL pattern. Most routes consist of a path and a component type.

Router Controls

CanAct­ivate
Checking route access
CanAct­iva­teChild
Checking child route access
CanDea­ctivate
Ask permission to discard unsaved changes
CanLoad
Check before loading feature module assets
 

Child Routes Definition

RouterModule.forChild([
      { path: 'heroes',  component: HeroListComponent },
      { path: 'hero/:id', component: HeroDetailComponent }
    ])
In the parent definition include the loadCh­ildren attributes

Lazy Loading Of Routes

export function loadCompensationModule() {
  return require('es6-promise!../cf/shell/shell.module')('ShellModule');
}


export const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full'},
  { path: 'cf', loadChildren: loadCompensationModule},
  { path: 'home', component: MainComponent, canActivate: [AuthGuard]},
  { path:'**', redirectTo: '' }
];

export const appRoutingProviders: any[] = [

];

export const routing: ModuleWithProviders = RouterModule.forRoot(routes, { useHash: false});
This is a sample. The children definition would be defined in the children array namely:

export const routes: Routes = [
{
path: '', component: ShellC­omp­onent,
children: [
{path: 'home', component: ShellC­omp­onent},
{path: 'one', loadCh­ildren: loadOn­eMo­dule},
{path: 'two', loadCh­ildren: loadTw­oMo­dule},
{path: 'three', loadCh­ildren: loadTh­ree­Mod­ule},
{path: 'four', loadCh­ildren: loadFo­urM­odule}
]
},
{path: '**', redire­ctTo: 'home'}
];

Route Parameters - Mandatory

Route Parameter
xxx/:{­type}
To Specify the route inform­ation
1. Construct the URL
2. Pass in this.r­out­er.n­av­iga­te(­['/­hero', hero.id]);

Route Paramters - Optional

<a [routerLink]="['/crisis-center', { foo: 'foo' }]">Crisis Center</a>

Location Stategy

PathLo­cat­ion­Str­ategy
the default "HTML 5 pushSt­ate­" style.
HashLo­cat­ion­Str­ategy
the "hash URL" style.
Router­Mod­ule.fo­rRo­ot(­routes, { useHash: true }) // .../#/­cri­sis­-ce­nter/
 

CanAct­ivate Guard

import { Injectable }       from '@angular/core';
import {
  CanActivate, Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
}                           from '@angular/router';
import { AuthService }      from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    let url: string = state.url;

    return this.checkLogin(url);
  }

  checkLogin(url: string): boolean {
    if (this.authService.isLoggedIn) { return true; }

    // Store the attempted URL for redirecting
    this.authService.redirectUrl = url;

    // Navigate to the login page with extras
    this.router.navigate(['/login']);
    return false;
  }
}
To reference the guard:

canAct­ivate: [AuthG­uard],

Route Animations

Import 

import { Component, OnInit, HostBinding,
         trigger, transition, animate,
         style, state } from '@angular/core';

animations: [
    trigger('routeAnimation', [
      state('*',
        style({
          opacity: 1,
          transform: 'translateX(0)'
        })
      ),
      transition('void => *', [
        style({
          opacity: 0,
          transform: 'translateX(-100%)'
        }),
        animate('0.2s ease-in')
      ]),
      transition('* => void', [
        animate('0.5s ease-out', style({
          opacity: 0,
          transform: 'translateY(100%)'
        }))
      ])
    ])
  ]

  @HostBinding('@routeAnimation') get routeAnimation() {
    return true;
  }
the host binding is for linking to the transition effect.
       
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Angular 2 Forms Cheat Sheet

          More Cheat Sheets by Nathane2005

          Angular2 Pipes Cheat Sheet
          Angular 2 Forms Cheat Sheet
          Angular 2 Http Cheat Sheet