Angular 4: Simple Routing

All code is on github
A demo is available on gh-pages

Start a new project using angular-cli,

$ ng new angularRouting

Move into the project root directory

$ cd angularRouting

Create app-routing.module.ts

$ ng g module app-routing

Set the app-routing.module.ts to add components and routes. Also note the changes to ngModule imports and exports.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { InfoComponent } from '../info/info.component'
import { AboutComponent } from '../about/about.component'

const routes: Routes = [
path: 'about',
component: AboutComponent,
path: 'info',
component: InfoComponent,

imports: [
exports: [
declarations: []
export class AppRoutingModule { }

Next create two components ‘about’ and ‘info’.

$ ng g c info
$ ng g c about

To app.module.ts import the AppRoutingModule and to ngModule imports add AppRoutingModule, so that app.module.ts looks like this,

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppRoutingModule } from './app-routing/app-routing.module';

import { AppComponent } from './app.component';
import { InfoComponent } from './info/info.component';
import { AboutComponent } from './about/about.component';

declarations: [
imports: [
providers: [],
bootstrap: [AppComponent]
export class AppModule { }

To app.component.html add the element. This is where the component will render. Also add link to the components,

<a routerLink="/info" routerLinkActive="active">Info</a>
<a routerLink="/about" routerLinkActive="active">About</a>

Add the following routes to redirect empty routes ” and wildcards ‘**’ to home,

path: '',
redirectTo: '/home',
pathMatch: 'full',
path: '**',
redirectTo: '/home',
pathMatch: 'full'

Note Angular checks the routes in order so empty routes and wildcards must be after all other routes with the wildcard route at the end.

All code is on github
and a demo is available on gh-pages

Useful link: