Table of Contents

Adding Router to App

Add the Routing Module

app-routing.module.ts will be add to project with the following code:

ng generate module app-routing --flat --module=app

Add Component for Routing to

Add a component for the router to route to. Here we have a component called mycom. A sub-directory with the component files will be generated under the directory src/app/.

ng generate component mycom

Route to a Component

In app-routing.module.ts, add

const routes: Routes = [
  { path: 'mycom', component: MycomComponent }
];

so that the file becomes:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import {Routes} from "@angular/router";
import {MycomComponent} from "./mycom/mycom.component";

const routes: Routes = [
  { path: '', redirectTo: '/mycom', pathMatch: 'full'},
  { path: 'mycom', component: MycomComponent }
];

@NgModule({
  declarations: [],
  imports: [
    CommonModule
  ]
})

export class AppRoutingModule {
}

Update the app.component.html

Set it as follow so that it will route the page according to the url.

<router-outlet></router-outlet>

When your URL is http://xxx.yyy:4200/mycom, the MycomComponent will show up.

Assume we have two other components called info and another, we can add the routes to our router module, and then do:

<a routerLinkActive="active" routerLink="info">info</a><br/>
<a routerLinkActive="active" routerLink="another">another</a>
<router-outlet></router-outlet>