Angular2 router

Features

  1. Component based navigation
  2. Nested views
    1. Sample use case: tabs
  3. CanActivate - Can navigate to component?
    1. Sample use case: restricted account page
  4. CanDeactivate - Can get out of component?
    1. Confirm changing route in edit page

ng g route

In current version of ng-cli, the generation of route is not possible. but ng g comopnent will be enough

  1. Create 'routes' folder under src/app
  2. Navigate to that folder
  3. Create route components:
    ng g component home-route
    ng g component event-route
    ng g component login-route
  4. Move app.component logic, imports to home-route component

Config routes

New file for defining the routes- app.routes.ts
​Locate it in src/app root folder

import { provideRouter, RouterConfig } from '@angular/router';
import { HomeRouteComponent } from './routes/home-route';
...

const routes: RouterConfig = [
  { path: '', component: HomeRouteComponent },
  { path: 'events/:slug', component: EventRouteComponent }
  ...
];

export const appRouterProviders = [
  provideRouter(routes)
];

Config routes

Add it to app bootstrap under main.ts

So the app will recognise the routes configured 

bootstrap(AppComponent, [
  ...
  appRouterProviders,
  ...
]);

Router outlet

placeholder element that will show the route component inside.

 

open app.component.html

<app-navbar></app-navbar>
<router-outlet></router-outlet>

Linking to route

  1. Import ROUTER_DIRECTIVES and use it app-wide:
    1. Add to bootstrap in main.ts





       
    2. import ROUTER_DIRECTIVES:
       
<a [routerLink]="['/events/' + event.slug]">{{event.title}}</a>

Using in template:

bootstrap(AppComponent, [
  ...
  provide(PLATFORM_DIRECTIVES,
    {
      useValue: [ROUTER_DIRECTIVES],
      multi: true
    })
  ...
]);
import { ROUTER_DIRECTIVES } from '@angular/router';

Get route param

  1. Import ActivatedRoute in the desired route component


     
  2. Use in constructor:

     
  3. Get the param:
import { ActivatedRoute } from '@angular/router';
ngOnInit() {
    this.route.params
      .map(params => params['id'])
      .subscribe((id) => {
        console.log(id)
      });
  }
constructor(private route: ActivatedRoute)

Angular2 Router

By Dvir Hazout

Angular2 Router

  • 632