Angular 4: Simple Routing

All code is on github https://github.com/shanegibney/angular-routing
A demo is available on gh-pages https://shanegibney.github.io/angular-routing/

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,
},
];

@NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [
RouterModule
],
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';

@NgModule({
declarations: [
AppComponent,
InfoComponent,
AboutComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AppRoutingModule,
],
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,

<h1>
{{title}}
</h1>
<a routerLink="/info" routerLinkActive="active">Info</a>
<a routerLink="/about" routerLinkActive="active">About</a>
<router-outlet></router-outlet>

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 https://github.com/shanegibney/angular-routing
and a demo is available on gh-pages https://shanegibney.github.io/angular-routing/

Useful link: http://shermandigital.com/blog/configure-routing-in-an-angular-cli-project/