Routing & Navigation with Angular 2's Router

Changing an Angular application's behavior based on where users navigate.

Eric Simons Up to date (Feb '19) Angular 2

While most developers chose to use 3rd party libraries like UI-Router to handle routing in Angular 1.x, Angular 2's router is excellent and provides virtually everything you'd ever need when it comes to routing.

To create routes is pretty simple — first you'll need to import the RouterModule:

import { RouterModule } from '@angular/router';

With that imported, what we can now do is create an instance of the RouterModule that will execute our desired routing functionality. To do that, you just pass an array of route objects to either the forRoot or forChild methods on the RouterModule (the docs explain the difference in detail, but for now just know that forRoot should only be called once in your app for top level routes):

const rootRouting: ModuleWithProviders = RouterModule.forRoot([
    path: '',
    component: HomeComponent
    path: 'profile',
    component: ProfileComponent
], { useHash: true });

For each route we provide a path (aka the URL) and the component that should be rendered at that path. The empty string for the HomeComponent's path means that the HomeComponent will be rendered when there is no URL (aka the root path).

You also may have noticed that we passed along { useHash: true } as the second argument — by default Angular 2 uses HTML5 location based routing, but that would require us to have a server set up that's smart enough to handle it. For the sake of simplicity we told Angular 2 to use hash based routing instead as it's guaranteed to work in virtually any environment setup.

Finally, to have our app use this routing functionality we simply import our new routing module into the app module:

  imports: [ 
+    rootRouting
  declarations: [
  bootstrap: [

The last thing you need to do is to give the router an outlet to render these components to as you navigate through the app. You can do this by placing a <router-outlet> component in the template wherever you want the routed components to be displayed:


You can view the working source code here:

Cool! So now that we have our routes set up, lets create the components that it renders and create links between them to demonstrate navigation functionality.