Getting Routed

How to add a route to a angular-cli project

This stuff is probablty good for standard angular-2 apps as well

This creates a public route called public

Generate a route

Create a route that's going to be publicall accessible (hence 'public'). The + that gets appended by the generator means it will lazy load the route

ng generate route public --default=true --inline-template=true
ng g route Private
ng g route NoPath

Add the paths to the main component

Anything not /private will be public

@Routes([
  new Route({ path: '/', component: PublicComponent }),
  new Route({ path: '/private', component: PrivateComponent }),
  new Route({ path: '*', component: NoPathComponent })
])

Update the template to display

<a [routerLink]="['/']">home</a>
<a [routerLink]="['/private']">private</a>
<router-outlet></router-outlet>

Add the provide to access the router information

@Component({
  // ...
  providers: [ROUTER_PROVIDERS]
  // ...
})

Reference the directives used by the component

Angular packages the common router directives (routerOutlet, routerLink) in ROUTERDIRECTIVES

@Component({
  //...
  directives: [ROUTER_DIRECTIVES, PrivateComponent, PublicComponent, NoPathComponent]
  // ...
})

Import all the used modules

import { ROUTER_DIRECTIVES, ROUTER_PROVIDERS, Routes, Route } from '@angular/router';
import { PublicComponent } from './+public';
import { PrivateComponent } from './+private';
import { NoPathComponent } from './+no-path';

Gotchas

Check for the import name by looking in the node_module\**\*.d.ts file exports. eg. @Routes not @RouteConfig

I needed to add a routerLink to the page before the router-outlet display the component.

Use the typescript Object (EG. new Route()) because you get editor goodness & type checking for free