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.
The Basics - Elements
There are four elements that work together to enable routing in Angular 2 and they are:
RouterConfig
- An array of routes you define where each route maps a URL path to a component
APP_ROUTER_PROVIDERS
- An array of arrays of Angular specific objects including a Router service provider that is generated when you pass your
RouterConfig
s to Angular'sprovideRouter()
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 <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:
- heroes.routes.ts (one or more files like this)
- It exports routes as a
RouterConfig
so app.routes.ts can import it - app.routes.ts (one file)
- It imports exported
RouterConfig
s soprovideRouter()
can use them as arguments to generate a Router service provider (among other things) and export asAPP_ROUTER_PROVIDERS
- main.ts (one file)
- It imports
APP_ROUTER_PROVIDERS
sobootstrap()
can use it as an argument to tell Angular about your application specific routes via the aforementioned generated Router service provider - 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