Show Menu

Angular 2 Router Cheat Sheet by

Ng2 Router

Getting started

In index.html

<base href="/">

Router Imports

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

Sample Router

      { 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


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 Link

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.
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.
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.
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.
Displays the applic­ation component for the active URL. Manages navigation from one component to the next.
A separate Angular module that provides the necessary service providers and directives for navigating through applic­ation views.
Defines an array of Routes, each mapping a URL path to a component.
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

Checking route access
Checking child route access
Ask permission to discard unsaved changes
Check before loading feature module assets

Child Routes Definition

      { 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
To Specify the route inform­ation
1. Construct the URL
2. Pass in this.r­out­er.n­av­iga­te(­['/­hero',]);

Route Paramters - Optional

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

Location Stategy

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

CanAct­ivate Guard

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

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
    return false;
To reference the guard:

canAct­ivate: [AuthG­uard],

Route Animations


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

animations: [
    trigger('routeAnimation', [
          opacity: 1,
          transform: 'translateX(0)'
      transition('void => *', [
          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.


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