Sharing Top Content from the Angular-sphere.

Routing Angular 2 Single Page Apps with the Component Router ― Scotch

Routing Angular 2 Single Page Apps with the Component Router

☞ 

#Angular2

  • routes.ts ====== – – // Imports – // Deprecated import – // import { provideRouter, RouterConfig } from ‘@angular/router’; – import { ModuleWithProviders } from ‘@angular/core’; – import { Routes, RouterModule } from ‘@angular/router’; – import { CatListComponent } from { DogListComponent } from Route Configuration – export const routes:…
  • // ====== ====== – – // Import component decorator – import { Component } from template: ` – h2Cats/h2 – pList of cats/p` – }) – – // Component class – export class CatListComponent {} – Just a basic Angular 2 component with a decorator and a component class.
  • // ====== ====== – – // Import component decorator – import { Component } from template: ` – h2Dogs/h2 – pList of dogs/p` – }) – – // Component class – export class DogListComponent {} – Bootstrapping Our Application – Before we bootstrap the app, we need to assemble our…
  • component.ts ====== – import { Component } from ‘@angular/core’; – // Import router directives – // Deprecated – // import { ROUTER_DIRECTIVES } from selector: ‘my-app’, – template: ` – div class=”demo-layout-transparent mdl-layout mdl-js-layout” – header class=”mdl-layout__header div !
  • — Router Outlet — – router-outlet/router-outlet – `, – // Not necessary as we have provided directives using – // `RouterModule` to root module – // Tell component to use router directives – // directives: [ROUTER_DIRECTIVES] – }) – – // App Component class – export class AppComponent {} -…

We have been so eager here at Scotch to create a comprehensive guide on Angular 2 Component Router. Now that a reliable version (v3) has been released (although alpha), it’s a good time then to discuss Component Router.

This article will serve as a guide to implementing routing in Angular 2 with a fully fleshed out example touching major aspects of routing including bootstrapping, configuration, parameterized routes, protecting routes, etc. In the past, we’ve looked at routing in Angular 1.x with ngRoute and UI-Router.

Take a look at what we’ll be building today:

Getting Started: App Setup

Angular 2 uses TypeScript, so if you need a refresher on that, take a look at why TypeScript is your friend and our TypeScript tutorial series.

Before we get started and to save us some setup time, clone the Angular 2 QuickStart then we can build on top of that.

git clone scotch-ng-router

The seed already has end to end tools to enable you start building Angular 2 apps. It also comes with all Angular 2 dependencies including angular/router so we can just pull the packages from npm:

npm install

We are more concerned with the app folder of our new project which is simply:

|—app

|—–main.ts…

Routing Angular 2 Single Page Apps with the Component Router ― Scotch