- var _example = 'toh-5';
block includes
include ../_util-fns
- var _appRoutingTsVsAppComp = 'app.routing.ts'
- var _declsVsDirectives = 'declarations'
- var _RoutesVsAtRouteConfig = 'Routes'
- var _RouterModuleVsRouterDirectives = 'RouterModule'
- var _redirectTo = 'redirectTo'
:marked
# Routing Around the App
We received new requirements for our Tour of Heroes application:
* Add a *Dashboard* view.
* Navigate between the *Heroes* and *Dashboard* views.
* Clicking on a hero in either view navigates to a detail view of the selected hero.
* Clicking a *deep link* in an email opens the detail view for a particular hero.
When we’re done, users will be able to navigate the app like this:
figure.image-display
img(src='/resources/images/devguide/toh/nav-diagram.png' alt="View navigations")
:marked
We'll add Angular’s *Component Router* to our app to satisfy these requirements.
.l-sub-section
:marked
The [Routing and Navigation](../guide/router.html) chapter covers the router
in more detail than we will in this tutorial.
:marked
Run the for this part.
+ifDocsFor('ts|js')
.l-sub-section
img(src='/resources/images/devguide/plunker-separate-window-button.png' alt="pop out the window" align="right" style="margin-right:-20px")
:marked
To see the URL changes in the browser address bar,
pop out the preview window by clicking the blue 'X' button in the upper right corner:
.l-main-section
:marked
## Where We Left Off
Before we continue with our Tour of Heroes, let’s verify that
we have the following structure after adding our hero service
and hero detail component. If not, we’ll need to go back and follow the previous chapters.
block intro-file-tree
.filetree
.file angular2-tour-of-heroes
.children
.file app
.children
.file app.component.ts
.file app.module.ts
.file hero.service.ts
.file hero.ts
.file hero-detail.component.ts
.file main.ts
.file mock-heroes.ts
.file node_modules ...
.file typings ...
.file index.html
.file package.json
.file styles.css
.file systemjs.config.js
.file tsconfig.json
.file typings.json
block keep-app-running
:marked
### Keep the app transpiling and running
Open a terminal/console window and enter the following command to
start the TypeScript compiler, start the server, and watch for changes:
code-example(language="bash").
npm start
:marked
The application runs and updates automatically as we continue to build the Tour of Heroes.
## Action plan
Here's our plan:
* Turn `AppComponent` into an application shell that only handles navigation
* Relocate the *Heroes* concerns within the current `AppComponent` to a separate `HeroesComponent`
* Add routing
* Create a new `DashboardComponent`
* Tie the *Dashboard* into the navigation structure
.l-sub-section
:marked
*Routing* is another name for *navigation*. The *router* is the mechanism for navigating from view to view.
.l-main-section
:marked
## Splitting the *AppComponent*
Our current app loads `AppComponent` and immediately displays the list of heroes.
Our revised app should present a shell with a choice of views (*Dashboard* and *Heroes*)
and then default to one of them.
The `AppComponent` should only handle navigation.
Let's move the display of *Heroes* out of `AppComponent` and into its own `HeroesComponent`.
### *HeroesComponent*
`AppComponent` is already dedicated to *Heroes*.
Instead of moving anything out of `AppComponent`, we'll just rename it `HeroesComponent`
and create a new `AppComponent` shell separately.
The steps are to rename:
* app.component.ts file to heroes.component.ts
* `AppComponent` class to `HeroesComponent`
* Selector `my-app` to `my-heroes`
+makeExcerpt('app/heroes.component.ts (showing renamings only)', 'renaming')
:marked
## Create *AppComponent*
The new `AppComponent` will be the application shell.
It will have some navigation links at the top and a display area below for the pages we navigate to.
The initial steps are:
* Create the file app/app.component.ts.
* Define an exported `AppComponent` class.
* Add an `@Component` !{_decorator} above the class with a `my-app` selector.
* Move the following from `HeroesComponent` to `AppComponent`:
* `title` class property
* `@Component` template `
` element, which contains a binding to `title`
* Add a `` element to the app template just below the heading so we still see the heroes.
* Add `HeroesComponent` to the `!{_declsVsDirectives}` !{_array} of `!{_AppModuleVsAppComp}` so Angular recognizes the `` tags.
* Add `HeroService` to the `providers` !{_array} of `!{_AppModuleVsAppComp}` because we'll need it in every other view.
* Remove `HeroService` from the `HeroesComponent` `providers` !{_array} since it has been promoted.
* Add the supporting `import` statements for `AppComponent`.
Our first draft looks like this:
block app-comp-v1
+makeTabs(
`toh-5/ts/app/app.component.1.ts,
toh-5/ts/app/app.module.1.ts`,
',',
`app/app.component.ts (v1),
app/app.module.ts (v1)`)
:marked
The app still runs and still displays heroes.
Our refactoring of `AppComponent` into a new `AppComponent` and a `HeroesComponent` worked!
We have done no harm.
:marked
## Add Routing
We're ready to take the next step.
Instead of displaying heroes automatically, we'd like to show them *after* the user clicks a button.
In other words, we'd like to navigate to the list of heroes.
We'll need the Angular *Component Router*.
block angular-router
:marked
The Angular router is an external, optional Angular NgModule called `RouterModule`.
The router is a combination of multiple provided services (`RouterModule`),
multiple directives (`RouterOutlet, RouterLink, RouterLinkActive`),
and a configuration (`Routes`). We'll configure our routes first.
:marked
### Add the base tag
Open `index.html` and add `` at the top of the `` section.
+makeExcerpt('index.html', 'base-href')
.callout.is-important
header base href is essential
:marked
See the *base href* section of the [Router](../guide/router.html#!#base-href)
chapter to learn why this matters.
a#configure-routes
block router-config-intro
:marked
### Configure routes
Our application doesn't have any routes yet.
We'll start by creating a configuration file for the application routes.
:marked
*Routes* tell the router which views to display when a user clicks a link or
pastes a URL into the browser address bar.
Let's define our first route as a route to the heroes component:
- var _file = _docsFor == 'dart' ? 'app.component.ts' : 'app.routing.ts'
+makeExcerpt('app/' + _file + ' (heroes route)', 'heroes')
- var _are = _docsFor == 'dart' ? 'takes' : 'are'
- var _routePathPrefix = _docsFor == 'dart' ? '/' : ''
:marked
The `!{_RoutesVsAtRouteConfig}` !{_are} !{_an} !{_array} of *route definitions*.
We have only one route definition at the moment but rest assured, we'll add more.
This *route definition* has the following parts:
- **path**: the router matches this route's path to the URL in the browser address bar (`!{_routePathPrefix}heroes`).
**name**: the official name of the route;
it *must* begin with a capital letter to avoid confusion with the *path* (`Heroes`).
- **component**: the component that the router should create when navigating to this route (`HeroesComponent`).
.l-sub-section
:marked
Learn more about defining routes with `!{_RoutesVsAtRouteConfig}` in the [Routing](../guide/router.html) chapter.
+ifDocsFor('ts|js')
:marked
We'll export a `routing` constant initialized using the `RouterModule.forRoot` method applied to our !{_array} of routes.
This method returns a **configured router module** that we'll add to our root NgModule, `AppModule`.
+makeExcerpt('app/app.routing.1.ts (excerpt)', 'routing-export')
.l-sub-section
:marked
We call the `forRoot` method because we're providing a configured router at the _root_ of the application.
The `forRoot` method gives us the Router service providers and directives needed for routing.
:marked
### Make the router available
We've setup initial routes in the `app.routing.ts` file. Now we'll add it to our root NgModule.
Import the `routing` constant from `app.routing.ts` and add it the `imports` !{_array} of `AppModule`.
+makeExcerpt('app/app.module.ts', 'routing')
- var _heroesRoute = _docsFor == 'dart' ? "'Heroes'" : 'heroes'
:marked
### Router Outlet
If we paste the path, `/heroes`, into the browser address bar,
the router should match it to the `!{_heroesRoute}` route and display the `HeroesComponent`.
But where?
We have to ***tell it where*** by adding a `` element to the bottom of the template.
`RouterOutlet` is one of the directives provided by the `!{_RouterModuleVsRouterDirectives}`.
The router displays each component immediately below the `` as we navigate through the application.
### Router Links
We don't really expect users to paste a route URL into the address bar.
We add an anchor tag to the template which, when clicked, triggers navigation to the `HeroesComponent`.
The revised template looks like this:
+makeExcerpt('app/app.component.1.ts', 'template-v2')
block routerLink
:marked
Notice the `routerLink` binding in the anchor tag.
We bind the `RouterLink` directive (another of the `RouterModule` directives) to a string
that tells the router where to navigate when the user clicks the link.
Since our link is not dynamic, we define a *routing instruction* with a **one-time binding** to our route **path**.
Looking back at the route configuration, we confirm that `'/heroes'` is the path of the route to the `HeroesComponent`.
.l-sub-section
:marked
Learn more about dynamic router links and the *link parameters array*
in the [Routing](../guide/router.html#link-parameters-array) chapter.
:marked
Refresh the browser. We see only the app title and heroes link. We don't see the heroes list.
.l-sub-section
:marked
The browser's address bar shows `/`.
The route path to `HeroesComponent` is `/heroes`, not `/`.
We don't have a route that matches the path `/`, so there is nothing to show.
That's something we'll want to fix.
:marked
We click the *Heroes* navigation link, the browser bar updates to `/heroes`,
and now we see the list of heroes. We are navigating at last!
At this stage, our `AppComponent` looks like this.
+makeExample('app/app.component.1.ts', 'v2', 'app/app.component.ts (v2)')
:marked
The *AppComponent* is now attached to a router and displaying routed views.
For this reason and to distinguish it from other kinds of components,
we call this type of component a *Router Component*.
:marked
## Add a *Dashboard*
Routing only makes sense when we have multiple views. We need another view.
Create a placeholder `DashboardComponent` that gives us something to navigate to and from.
+makeExcerpt('app/dashboard.component.1.ts (v1)', '')
:marked
We’ll come back and make it more useful later.
### Configure the dashboard route
Go back to `!{_appRoutingTsVsAppComp}` and teach it to navigate to the dashboard.
Import the dashboard component and
add the following route definition to the `!{_RoutesVsAtRouteConfig}` !{_array} of definitions.
- var _file = _docsFor == 'dart' ? 'lib/app_component.dart' : 'app/app.routing.ts'
+makeExcerpt(_file + ' (Dashboard route)', 'dashboard')
+ifDocsFor('ts|js')
:marked
Also import and add `DashboardComponent` to our root NgModule's `declarations`.
+makeExcerpt('app/app.module.ts', 'dashboard')
:marked
#### !{_redirectTo}
We want the app to show the dashboard when it starts and
we want to see a nice URL in the browser address bar that says `/dashboard`.
Remember that the browser launches with `/` in the address bar.
block redirect-vs-use-as-default
:marked
We can use a redirect route to make this happen. Add the following
to our array of route definitions:
+makeExcerpt('app/app.routing.ts','redirect')
.l-sub-section
:marked
Learn about the *redirects* in the [Routing](../guide/router.html#!#redirect) chapter.
:marked
#### Add navigation to the template
Finally, add a dashboard navigation link to the template, just above the *Heroes* link.
- var _vers = _docsFor == 'dart' ? '' : '.1'
+makeExcerpt('app/app.component' + _vers + '.ts', 'template-v3')
.l-sub-section
:marked
We nestled the two links within `