Category
Software Engineering

Published
July 13, 2016

Read
2 min

Tweet
Share
Comment

Angular 2 Routing - The Basics

Article Purpose

The purpose of this article is to outline the four basic elements a developer must implement to enable routing in an Angular 2 application. Understanding these four elements makes it easier to grasp how the code you write is used by Angular 2 to enable routing within an application.

There is more to routing in Angular 2 than I will cover below so I recommend Thoughtram.io's Routing in Angular 2 Revisited post. I also highly recommend the Angular 2 Routing Docs for more detail.

The Basics - Elements

There are four elements that work together to enable routing in Angular 2 and they are:

  1. RouterConfig
    • An array of routes you define where each route maps a URL path to a component
  2. APP_ROUTER_PROVIDERS
    • An array of arrays of Angular specific objects including a Router service provider that is generated when you pass your RouterConfigs to Angular's provideRouter()
  3. bootstrap()
    • The app point-of-entry where APP_ROUTER_PROVIDERS is passed in as an argument so Angular will leverage the aforementioned Router service provider you helped Angular generate
  4. <router-outlet>
    • An Angular directive you place in a template so Angular knows where to inject a component based on a route path

The Basics - Files

The files referenced below are found in this plnkr which is a simplified version of Angular 2's Tour of Heroes Routing Example linked to from the Routing docs.

In the example plnkr there are four files which map one-to-one to the four aforementioned elements above. They are:

  1. heroes.routes.ts (one or more files like this)
    • It exports routes as a RouterConfig so app.routes.ts can import it
  2. app.routes.ts (one file)
    • It imports exported RouterConfigs so provideRouter() can use them as arguments to generate a Router service provider (among other things) and export as APP_ROUTER_PROVIDERS
  3. main.ts (one file)
    • It imports APP_ROUTER_PROVIDERS so bootstrap() can use it as an argument to tell Angular about your application specific routes via the aforementioned generated Router service provider
  4. app.component.ts (one or more files like this)
    • It provides a <router-outlet> so Angular knows where to inject a component based on a route path

If you want to see the code for the above mentioned files then check out the plnkr.

Plnkr