Angular 2 Router Example

Use the Angular router to navigate between components when the user clicks a link. We take a look at routerLink, routerLinkActive, <router-outlet> and more.

Updated Nov 2017, Angular version 5.0

The Application

This is the simple demo application we will be using. We'll see how the router manages the contents of the colored area whenever a link is clicked. Go ahead, give it a try.

The Menu

First let's take a look at our menu. The routerLink directive on the anchor element is bound to a string containing the path of a route. We see how the router handles these paths in the next section.

We also include a <router-outlet> element in the template. This is where the content is rendered by the router when a particular route is selected. So when the user clicks one of the links, or types the path in the address bar (e.g. http://example.com#/green), the router will output the appropriate content in <router-outlet>.

Also, routerLinkActive adds the CSS class in quotes to the anchor element when the route is active, effectively disabling the link.

app.component.ts
import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-router',
  template: `
    <div>
      <p>
        <a routerLink="/red" routerLinkActive="disabled">Red</a> |
        <a routerLink="/green" routerLinkActive="disabled">Green</a> |
        <a routerLink="/blue" routerLinkActive="disabled">Blue</a>
      </p>
      <div class="border not-padded">
        <router-outlet></router-outlet>
      </div>
    </div>`,
  styles: [`
    div {
      padding: 10px;
    }
    .not-padded {
      padding: 0;
    }
    .border {
      border: 1px solid #b3b3b3;
    }
    .disabled {
      pointer-events: none;
      cursor: default;
      color: #404040;
      text-decoration: none;
    }`
  ],
  encapsulation: ViewEncapsulation.None
})
export class AppComponent {
}

Routes

Next we configure the router to handle the red, green and blue paths that we specified in the routerLink directives in our menu.

To do this, we build an array of objects which map our paths to a particular component. We include a redirectTo entry which provides a default route by redirecting to /green when the path is empty.

This array is then passed into the forRoot method of RouterModule. The return value from this method is exported so that we can include it in our module.

app.routes.ts
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { RedComponent } from './red.component';
import { GreenComponent } from './green.component';
import { BlueComponent } from './blue.component';

const routes: Routes = [
  {path: '', redirectTo: '/green', pathMatch: 'full'},
  {path: 'red', component: RedComponent},
  {path: 'green', component: GreenComponent},
  {path: 'blue', component: BlueComponent},
];

export const routing: ModuleWithProviders = RouterModule.forRoot(routes);

NgModule

Our route definitions are added to the module by including the routing variable in the imports property of the @NgModule directive.

HashLocationStrategy is a LocationStrategy which tells Angular to represent its state in the hash fragment of the browser's URL, for example http://example.com#/red. This overrides the default of PathLocationStrategy which produces a URL like this: http://example.com/red.

app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HashLocationStrategy, LocationStrategy } from '@angular/common';

import { AppComponent } from './app.component';
import { routing } from './app.routes';
import { RedComponent } from './red.component';
import { GreenComponent } from './green.component';
import { BlueComponent } from './blue.component';

@NgModule({
  imports: [
    BrowserModule,
    routing
  ],
  declarations: [
    AppComponent,
    BlueComponent,
    GreenComponent,
    RedComponent
  ],
  bootstrap: [
    AppComponent
  ],
  providers: [
    {provide: LocationStrategy, useClass: HashLocationStrategy}
  ]
})
export class AppModule {
}

Summary

So when the user clicks one of the links in the menu, the router will map the path to a component, and render the view in <router-outlet>. When a route is active, routerLinkActive disables the link by adding the disabled class to the element

app.component.ts
import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-router',
  template: `
    <div>
      <p>
        <a routerLink="/red" routerLinkActive="disabled">Red</a> |
        <a routerLink="/green" routerLinkActive="disabled">Green</a> |
        <a routerLink="/blue" routerLinkActive="disabled">Blue</a>
      </p>
      <div class="border not-padded">
        <router-outlet></router-outlet>
      </div>
    </div>`,
  styles: [`
    div {
      padding: 10px;
    }
    .not-padded {
      padding: 0;
    }
    .border {
      border: 1px solid #b3b3b3;
    }
    .disabled {
      pointer-events: none;
      cursor: default;
      color: #404040;
      text-decoration: none;
    }`
  ],
  encapsulation: ViewEncapsulation.None
})
export class AppComponent {
}

Where Next?

To find out more about Angular and TypeScript, check out these tutorials.

  • Hello World - Implement a super-simple <hello-world> custom element using an Angular and TypeScript.
  • The Angular with TypeScript Tutorial - includes examples of components, template syntax, property binding, event binding, bootstrapping and more.
  • Configuration - Configure Angular and TypeScript to download dependencies from node modules or a CDN, and to compile the TypeScript during development or in the browser at runtime.
  • Templates - introduction to inline and external templates.
  • Interpolation - use curly braces and template expressions to output data on the page.
  • Property Binding - bind to DOM properties using square brackets and template expressions.
  • Event Binding - handle DOM events using parentheses and template statements.
  • Two-way Binding - combine property and event binding to create two-way binding with ngModel.
  • Input Binding - bind to <input> fields such as text, textarea, checkbox, radio and select.
  • Built-in Directives - see how to use built-in directives ngIf, ngSwitch, ngFor, ngClass and ngStyle.
  • Component Input Output - use @Input and @Output to pass data in to and out of a component.
  • Nested Child Routes - An example of how child routes allow navigation between multiple views when a user clicks a link in a sub-menu.