docs(toh-5): Upgraded tutorial to new router

This commit is contained in:
Brandon Roberts 2016-06-19 00:20:38 -04:00 committed by Naomi Black
parent 2eae445504
commit f3189546a6
15 changed files with 364 additions and 267 deletions

View File

@ -1,20 +1,20 @@
/* Master Styles */ /* Master Styles */
h1 { h1 {
color: #369; color: #369;
font-family: Arial, Helvetica, sans-serif; font-family: Arial, Helvetica, sans-serif;
font-size: 250%; font-size: 250%;
} }
h2, h3 { h2, h3 {
color: #444; color: #444;
font-family: Arial, Helvetica, sans-serif; font-family: Arial, Helvetica, sans-serif;
font-weight: lighter; font-weight: lighter;
} }
body { body {
margin: 2em; margin: 2em;
} }
body, input[text], button { body, input[text], button {
color: #888; color: #888;
font-family: Cambria, Georgia; font-family: Cambria, Georgia;
} }
a { a {
cursor: pointer; cursor: pointer;
@ -34,7 +34,7 @@ button:hover {
} }
button:disabled { button:disabled {
background-color: #eee; background-color: #eee;
color: #aaa; color: #aaa;
cursor: auto; cursor: auto;
} }
@ -54,7 +54,7 @@ nav a:hover {
color: #039be5; color: #039be5;
background-color: #CFD8DC; background-color: #CFD8DC;
} }
nav a.router-link-active { nav a.active {
color: #039be5; color: #039be5;
} }
@ -137,6 +137,6 @@ nav a.router-link-active {
} }
/* everywhere else */ /* everywhere else */
* { * {
font-family: Arial, Helvetica, sans-serif; font-family: Arial, Helvetica, sans-serif;
} }

View File

@ -8,7 +8,7 @@ import { HeroesComponent } from './heroes.component';
// #enddocregion // #enddocregion
// For testing only // For testing only
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router-deprecated'; import { ROUTER_DIRECTIVES } from '@angular/router';
// #docregion // #docregion
@Component({ @Component({
@ -20,7 +20,6 @@ import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/route
directives: [HeroesComponent], directives: [HeroesComponent],
providers: [ providers: [
// #enddocregion // #enddocregion
ROUTER_PROVIDERS,
// #docregion // #docregion
HeroService HeroService
] ]

View File

@ -2,38 +2,27 @@
// #docregion // #docregion
import { Component } from '@angular/core'; import { Component } from '@angular/core';
// #docregion import-router // #docregion import-router
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router-deprecated'; import { ROUTER_DIRECTIVES } from '@angular/router';
// #enddocregion import-router // #enddocregion import-router
import { HeroService } from './hero.service'; import { HeroService } from './hero.service';
import { HeroesComponent } from './heroes.component';
@Component({ @Component({
selector: 'my-app', selector: 'my-app',
// #docregion template // #docregion template
template: ` template: `
<h1>{{title}}</h1> <h1>{{title}}</h1>
<a [routerLink]="['Heroes']">Heroes</a> <a [routerLink]="['/heroes']">Heroes</a>
<router-outlet></router-outlet> <router-outlet></router-outlet>
`, `,
// #enddocregion template // #enddocregion template
// #docregion directives-and-providers // #docregion directives-and-providers
directives: [ROUTER_DIRECTIVES], directives: [ROUTER_DIRECTIVES],
providers: [ providers: [
ROUTER_PROVIDERS,
HeroService HeroService
] ]
// #enddocregion directives-and-providers // #enddocregion directives-and-providers
}) })
// #docregion route-config
@RouteConfig([
{
path: '/heroes',
name: 'Heroes',
component: HeroesComponent
}
])
// #enddocregion route-config
export class AppComponent { export class AppComponent {
title = 'Tour of Heroes'; title = 'Tour of Heroes';
} }

View File

@ -0,0 +1,33 @@
// #docplaster
// #docregion
import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
import { HeroService } from './hero.service';
@Component({
selector: 'my-app',
// #docregion template
template: `
<h1>{{title}}</h1>
<nav>
// #docregion router-link-active
<a [routerLink]="['/dashboard']" routerLinkActive="active">Dashboard</a>
<a [routerLink]="['/heroes']" routerLinkActive="active">Heroes</a>
// #enddocregion router-link-active
</nav>
<router-outlet></router-outlet>
`,
// #enddocregion template
// #docregion style-urls
styleUrls: ['app/app.component.css'],
// #enddocregion style-urls
directives: [ROUTER_DIRECTIVES],
providers: [
HeroService
]
})
export class AppComponent {
title = 'Tour of Heroes';
}
// #enddocregion

View File

@ -24,6 +24,6 @@ nav a:hover {
color: #039be5; color: #039be5;
background-color: #CFD8DC; background-color: #CFD8DC;
} }
nav a.router-link-active { nav a.active {
color: #039be5; color: #039be5;
} }

View File

@ -1,13 +1,8 @@
// #docplaster // #docplaster
// #docregion // #docregion
import { Component } from '@angular/core'; import { Component } from '@angular/core';
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router-deprecated'; import { ROUTER_DIRECTIVES } from '@angular/router';
import { DashboardComponent } from './dashboard.component';
import { HeroesComponent } from './heroes.component';
// #docregion hero-detail-import
import { HeroDetailComponent } from './hero-detail.component';
// #enddocregion hero-detail-import
import { HeroService } from './hero.service'; import { HeroService } from './hero.service';
@Component({ @Component({
@ -16,8 +11,8 @@ import { HeroService } from './hero.service';
template: ` template: `
<h1>{{title}}</h1> <h1>{{title}}</h1>
<nav> <nav>
<a [routerLink]="['Dashboard']">Dashboard</a> <a [routerLink]="['/dashboard']" routerLinkActive="active">Dashboard</a>
<a [routerLink]="['Heroes']">Heroes</a> <a [routerLink]="['/heroes']" routerLinkActive="active">Heroes</a>
</nav> </nav>
<router-outlet></router-outlet> <router-outlet></router-outlet>
`, `,
@ -27,32 +22,9 @@ import { HeroService } from './hero.service';
// #enddocregion style-urls // #enddocregion style-urls
directives: [ROUTER_DIRECTIVES], directives: [ROUTER_DIRECTIVES],
providers: [ providers: [
ROUTER_PROVIDERS,
HeroService HeroService
] ]
}) })
@RouteConfig([
// #docregion dashboard-route
{
path: '/dashboard',
name: 'Dashboard',
component: DashboardComponent,
useAsDefault: true
},
// #enddocregion dashboard-route
// #docregion hero-detail-route
{
path: '/detail/:id',
name: 'HeroDetail',
component: HeroDetailComponent
},
// #enddocregion hero-detail-route
{
path: '/heroes',
name: 'Heroes',
component: HeroesComponent
}
])
export class AppComponent { export class AppComponent {
title = 'Tour of Heroes'; title = 'Tour of Heroes';
} }

View File

@ -0,0 +1,37 @@
// #docregion
import { provideRouter, RouterConfig } from '@angular/router';
import { DashboardComponent } from './dashboard.component';
import { HeroesComponent } from './heroes.component';
// #docregion hero-detail-import
import { HeroDetailComponent } from './hero-detail.component';
// #enddocregion hero-detail-import
export const routes: RouterConfig = [
// #docregion redirect-route
{
path: '',
redirectTo: '/dashboard',
terminal: true
},
// #enddocregion redirect-route
// #docregion dashboard-route
{
path: 'dashboard',
component: DashboardComponent
},
// #enddocregion dashboard-route
// #docregion hero-detail-route
{
path: 'detail/:id',
component: HeroDetailComponent
},
// #enddocregion hero-detail-route
{
path: 'heroes',
component: HeroesComponent
}
];
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes)
];

View File

@ -0,0 +1,14 @@
// #docregion
import { provideRouter, RouterConfig } from '@angular/router';
import { HeroesComponent } from './heroes.component';
const routes: RouterConfig = [
{
path: '/heroes',
component: HeroesComponent
}
];
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes)
];

View File

@ -0,0 +1,32 @@
// #docregion
import { provideRouter, RouterConfig } from '@angular/router';
import { DashboardComponent } from './dashboard.component';
import { HeroesComponent } from './heroes.component';
// #docregion hero-detail-import
import { HeroDetailComponent } from './hero-detail.component';
// #enddocregion hero-detail-import
export const routes: RouterConfig = [
{
path: '',
redirectTo: '/dashboard',
terminal: true
},
{
path: 'dashboard',
component: DashboardComponent
},
{
path: 'detail/:id',
component: HeroDetailComponent
},
{
path: 'heroes',
component: HeroesComponent
}
];
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes)
];

View File

@ -2,7 +2,7 @@
// #docregion // #docregion
import { Component, OnInit } from '@angular/core'; import { Component, OnInit } from '@angular/core';
// #docregion import-router // #docregion import-router
import { Router } from '@angular/router-deprecated'; import { Router } from '@angular/router';
// #enddocregion import-router // #enddocregion import-router
import { Hero } from './hero'; import { Hero } from './hero';
@ -36,7 +36,7 @@ export class DashboardComponent implements OnInit {
// #docregion goto-detail // #docregion goto-detail
gotoDetail(hero: Hero) { gotoDetail(hero: Hero) {
let link = ['HeroDetail', { id: hero.id }]; let link = ['/detail', hero.id];
this.router.navigate(link); this.router.navigate(link);
} }
// #enddocregion goto-detail // #enddocregion goto-detail

View File

@ -1,11 +1,11 @@
// #docplaster // #docplaster
// #docregion // #docregion
// #docregion import-oninit, v2 // #docregion import-oninit, v2
import { Component, OnInit } from '@angular/core'; import { Component, OnInit, OnDestroy } from '@angular/core';
// #enddocregion import-oninit // #enddocregion import-oninit
// #docregion import-route-params // #docregion import-activated-route
import { RouteParams } from '@angular/router-deprecated'; import { ActivatedRoute } from '@angular/router';
// #enddocregion import-route-params // #enddocregion import-activated-route
import { Hero } from './hero'; import { Hero } from './hero';
// #docregion import-hero-service // #docregion import-hero-service
@ -23,27 +23,36 @@ import { HeroService } from './hero.service';
}) })
// #enddocregion extract-template // #enddocregion extract-template
// #docregion implement // #docregion implement
export class HeroDetailComponent implements OnInit { export class HeroDetailComponent implements OnInit, OnDestroy {
// #enddocregion implement // #enddocregion implement
hero: Hero; hero: Hero;
sub: any;
// #docregion ctor // #docregion ctor
constructor( constructor(
private heroService: HeroService, private heroService: HeroService,
private routeParams: RouteParams) { private route: ActivatedRoute) {
} }
// #enddocregion ctor // #enddocregion ctor
// #docregion ng-oninit // #docregion ng-oninit
ngOnInit() { ngOnInit() {
// #docregion get-id // #docregion get-id
let id = +this.routeParams.get('id'); this.sub = this.route.params.subscribe(params => {
let id = +params['id'];
this.heroService.getHero(id)
.then(hero => this.hero = hero);
});
// #enddocregion get-id // #enddocregion get-id
this.heroService.getHero(id)
.then(hero => this.hero = hero);
} }
// #enddocregion ng-oninit // #enddocregion ng-oninit
// #docregion ng-ondestroy
ngOnDestroy() {
this.sub.unsubscribe();
}
// #enddocregion ng-ondestroy
// #docregion go-back // #docregion go-back
goBack() { goBack() {
window.history.back(); window.history.back();

View File

@ -1,7 +1,7 @@
// #docplaster // #docplaster
// #docregion // #docregion
import { Component, OnInit } from '@angular/core'; import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router-deprecated'; import { Router } from '@angular/router';
import { Hero } from './hero'; import { Hero } from './hero';
import { HeroService } from './hero.service'; import { HeroService } from './hero.service';
@ -36,7 +36,7 @@ export class HeroesComponent implements OnInit {
onSelect(hero: Hero) { this.selectedHero = hero; } onSelect(hero: Hero) { this.selectedHero = hero; }
gotoDetail() { gotoDetail() {
this.router.navigate(['HeroDetail', { id: this.selectedHero.id }]); this.router.navigate(['/detail', this.selectedHero.id]);
} }
// #docregion heroes-component-renaming // #docregion heroes-component-renaming
} }

View File

@ -1,5 +1,9 @@
// #docregion
import { bootstrap } from '@angular/platform-browser-dynamic'; import { bootstrap } from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component'; import { AppComponent } from './app.component';
import { APP_ROUTER_PROVIDERS } from './app.routes';
bootstrap(AppComponent); bootstrap(AppComponent, [
APP_ROUTER_PROVIDERS
]);

View File

@ -3,7 +3,7 @@
"files":[ "files":[
"!**/*.d.ts", "!**/*.d.ts",
"!**/*.js", "!**/*.js",
"!**/*.[1,2].*" "!**/*.[1,2,3].*"
], ],
"tags": ["tutorial", "tour", "heroes", "router"] "tags": ["tutorial", "tour", "heroes", "router"]
} }

View File

@ -2,12 +2,12 @@ include ../_util-fns
:marked :marked
# Routing Around the App # Routing Around the App
We received new requirements for our Tour of Heroes application: We received new requirements for our Tour of Heroes application:
* Add a *Dashboard* view. * Add a *Dashboard* view.
* Navigate between the *Heroes* and *Dashboard* views. * Navigate between the *Heroes* and *Dashboard* views.
* Clicking on a hero in either view navigates to a detail view of the selected hero. * 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; * Clicking a *deep link* in an email opens the detail view for a particular hero;
When were done, users will be able to navigate the app like this: When were done, users will be able to navigate the app like this:
figure.image-display figure.image-display
img(src='/resources/images/devguide/toh/nav-diagram.png' alt="View navigations") img(src='/resources/images/devguide/toh/nav-diagram.png' alt="View navigations")
@ -15,21 +15,21 @@ figure.image-display
We'll add Angulars *Component Router* to our app to satisfy these requirements. We'll add Angulars *Component Router* to our app to satisfy these requirements.
.l-sub-section .l-sub-section
:marked :marked
The [Routing and Navigation](../guide/router-deprecated.html) chapter covers the router in more detail The [Routing and Navigation](../guide/router.html) chapter covers the router in more detail
than we will in this tutorial. than we will in this tutorial.
p Run the #[+liveExampleLink2('', 'toh-5')] for this part. p Run the #[+liveExampleLink2('', 'toh-5')] for this part.
.l-sub-section .l-sub-section
img(src='/resources/images/devguide/plunker-separate-window-button.png' alt="pop out the window" align="right" style="margin-right:-20px") img(src='/resources/images/devguide/plunker-separate-window-button.png' alt="pop out the window" align="right" style="margin-right:-20px")
:marked :marked
To see the URL changes in the browser address bar, 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: pop out the preview window by clicking the blue 'X' button in the upper right corner:
.l-main-section .l-main-section
:marked :marked
## Where We Left Off ## Where We Left Off
Before we continue with our Tour of Heroes, lets verify that we have the following structure after adding our hero service Before we continue with our Tour of Heroes, lets verify that we have the following structure after adding our hero service
and hero detail component. If not, well need to go back and follow the previous chapters. and hero detail component. If not, well need to go back and follow the previous chapters.
.filetree .filetree
@ -44,7 +44,7 @@ p Run the #[+liveExampleLink2('', 'toh-5')] for this part.
.file main.ts .file main.ts
.file mock-heroes.ts .file mock-heroes.ts
.file node_modules ... .file node_modules ...
.file typings ... .file typings ...
.file index.html .file index.html
.file package.json .file package.json
.file styles.css .file styles.css
@ -64,7 +64,7 @@ code-example(language="bash").
## Action plan ## Action plan
Here's our plan: Here's our plan:
* Turn `AppComponent` into an application shell that only handles navigation * Turn `AppComponent` into an application shell that only handles navigation
* Relocate the *Heroes* concerns within the current `AppComponent` to a separate `HeroesComponent` * Relocate the *Heroes* concerns within the current `AppComponent` to a separate `HeroesComponent`
* Add routing * Add routing
@ -74,13 +74,13 @@ code-example(language="bash").
.l-sub-section .l-sub-section
:marked :marked
*Routing* is another name for *navigation*. The *router* is the mechanism for navigating from view to view. *Routing* is another name for *navigation*. The *router* is the mechanism for navigating from view to view.
.l-main-section .l-main-section
:marked :marked
## Splitting the *AppComponent* ## Splitting the *AppComponent*
Our current app loads `AppComponent` and immediately displays the list of heroes. 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. 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. The `AppComponent` should only handle navigation.
@ -101,11 +101,11 @@ code-example(language="bash").
:marked :marked
## Create *AppComponent* ## Create *AppComponent*
The new `AppComponent` will be the application shell. 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. It will have some navigation links at the top and a display area below for the pages we navigate to.
The initial steps are: The initial steps are:
* create a new file named `app.component.ts`. * create a new file named `app.component.ts`.
* define an `AppComponent` class. * define an `AppComponent` class.
* `export` it so we can reference it during bootstrapping in `main.ts`. * `export` it so we can reference it during bootstrapping in `main.ts`.
@ -116,7 +116,7 @@ code-example(language="bash").
* add the `HeroesComponent` to the `directives` array so Angular recognizes the `<my-heroes>` tags. * add the `HeroesComponent` to the `directives` array so Angular recognizes the `<my-heroes>` tags.
* add the `HeroService` to the `providers` array because we'll need it in every other view. * add the `HeroService` to the `providers` array because we'll need it in every other view.
* add the supporting `import` statements. * add the supporting `import` statements.
Our first draft looks like this: Our first draft looks like this:
+makeExample('toh-5/ts/app/app.component.1.ts', null, 'app/app.component.ts (v1)') +makeExample('toh-5/ts/app/app.component.1.ts', null, 'app/app.component.ts (v1)')
:marked :marked
@ -127,104 +127,99 @@ code-example(language="bash").
We are *promoting* this service from the `HeroesComponent` to the `AppComponent`. We are *promoting* this service from the `HeroesComponent` to the `AppComponent`.
We ***do not want two copies*** of this service at two different levels of our app. We ***do not want two copies*** of this service at two different levels of our app.
:marked :marked
The app still runs and still displays heroes. The app still runs and still displays heroes.
Our refactoring of `AppComponent` into a new `AppComponent` and a `HeroesComponent` worked! Our refactoring of `AppComponent` into a new `AppComponent` and a `HeroesComponent` worked!
We have done no harm. We have done no harm.
:marked :marked
## Add Routing ## Add Routing
We're ready to take the next step. 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. 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. In other words, we'd like to navigate to the list of heroes.
We'll need the Angular *Component Router*. We'll need the Angular *Component Router*.
### Set the base tag ### Set the base tag
Open the `index.html` and add `<base href="/">` at the top of the `<head>` section. Open the `index.html` and add `<base href="/">` at the top of the `<head>` section.
+makeExample('toh-5/ts/index.html', 'base-href', 'index.html (base href)')(format=".") +makeExample('toh-5/ts/index.html', 'base-href', 'index.html (base href)')(format=".")
.callout.is-important .callout.is-important
header base href is essential header base href is essential
:marked :marked
See the *base href* section of the [Router](../guide/router-deprecated.html#!#base-href) chapter to learn why this matters. See the *base href* section of the [Router](../guide/router.html#!#base-href) chapter to learn why this matters.
:marked :marked
### Make the router available. The Angular router is a combination of multiple provided services (`provideRouter`), multiple directives (`ROUTER_DIRECTIVES`),
The *Component Router* is a service. Like any service, we have to import it and make it and a configuration (`RouterConfig`). We'll configure our routes first:
available to the application by adding it to the `providers` array.
### Configure and add the router
The Angular router is a combination of multiple services (`ROUTER_PROVIDERS`), multiple directives (`ROUTER_DIRECTIVES`),
and a configuration decorator (`RouteConfig`). We'll import them all together: Our application doesn't have a router yet. We'll create a configuration file for our routes that
+makeExample('toh-5/ts/app/app.component.2.ts', 'import-router', 'app/app.component.ts (router imports)')(format=".") does two things
:marked (a) configure that router with *routes*. (b) provide an export to add the router to our bootstrap
Next we update the `directives` and `providers` metadata arrays to *include* the router assets.
+makeExample('toh-5/ts/app/app.component.2.ts', 'directives-and-providers', 'app/app.component.ts (directives and providers)')(format=".") *Routes* tell the router which views to display when a user clicks a link or
:marked
Notice that we also removed the `HeroesComponent` from the `directives` array.
`AppComponent` no longer shows heroes; that will be the router's job.
We'll soon remove `<my-heroes>` from the template too.
### Add and configure the router
The `AppComponent` doesn't have a router yet. We'll use the `@RouteConfig` decorator to simultaneously
(a) assign a router to the component and (b) configure that router with *routes*.
*Routes* tell the router which views to display when a user clicks a link or
pastes a URL into the browser address bar. pastes a URL into the browser address bar.
Let's define our first route, a route to the `HeroesComponent`. Let's define our first route, a route to the `HeroesComponent`.
+makeExample('toh-5/ts/app/app.component.2.ts', 'route-config', 'app/app.component.ts (RouteConfig for heroes)')(format=".") +makeExample('toh-5/ts/app/app.routes.2.ts', '', 'app/app.routes.ts')(format=".")
:marked :marked
`@RouteConfig` takes an array of *route definitions*. The `RouterConfig` is an array of *route definitions*.
We have only one route definition at the moment but rest assured, we'll add more. We have only one route definition at the moment but rest assured, we'll add more.
This *route definition* has three parts: This *route definition* has two parts:
* **path**: the router matches this route's path to the URL in the browser address bar (`/heroes`). * **path**: the router matches this route's path to the URL in the browser address bar (`/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`). * **component**: the component that the router should create when navigating to this route (`HeroesComponent`).
.l-sub-section .l-sub-section
:marked :marked
Learn more about defining routes with @RouteConfig in the [Routing](../guide/router-deprecated.html) chapter. Learn more about defining routes with RouterConfig in the [Routing](../guide/router.html) chapter.
:marked
### Make the router available.
The *Component Router* is a service. We have to import our `APP_ROUTER_PROVIDERS` which
contains our configured router and make it available to the application by adding it to
the `bootstrap` array.
+makeExample('toh-5/ts/app/main.ts', '', 'app/main.ts')(format=".")
:marked :marked
### Router Outlet ### Router Outlet
If we paste the path, `/heroes`, into the browser address bar, If we paste the path, `/heroes`, into the browser address bar,
the router should match it to the `'Heroes'` route and display the `HeroesComponent`. the router should match it to the `'Heroes'` route and display the `HeroesComponent`.
But where? But where?
We have to ***tell it where*** by adding `<router-outlet>` marker tags to the bottom of the template. We have to ***tell it where*** by adding `<router-outlet>` marker tags to the bottom of the template.
`RouterOutlet` is one of the `ROUTER_DIRECTIVES`. `RouterOutlet` is one of the `ROUTER_DIRECTIVES`.
The router displays each component immediately below the `<router-outlet>` as we navigate through the application. The router displays each component immediately below the `<router-outlet>` as we navigate through the application.
### Router Links ### Router Links
We don't really expect users to paste a route URL into the address bar. 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`. We add an anchor tag to the template which, when clicked, triggers navigation to the `HeroesComponent`.
The revised template looks like this: The revised template looks like this:
+makeExample('toh-5/ts/app/app.component.2.ts', 'template', 'app/app.component.ts (template v1)')(format=".") +makeExample('toh-5/ts/app/app.component.2.ts', 'template', 'app/app.component.ts (template v1)')(format=".")
:marked :marked
Notice the `[routerLink]` binding in the anchor tag. Notice the `[routerLink]` binding in the anchor tag.
We bind the `RouterLink` directive (another of the `ROUTER_DIRECTIVES`) to an array We bind the `RouterLink` directive (another of the `ROUTER_DIRECTIVES`) to an array
that tells the router where to navigate when the user clicks the link. that tells the router where to navigate when the user clicks the link.
We define a *routing instruction* with a *link parameters array*. We define a *routing instruction* with a *link parameters array*.
The array only has one element in our little sample, the quoted ***name* of the route** to follow. The array only has one element in our little sample, the quoted ***path* of the route** to follow.
Looking back at the route configuration, we confirm that `'Heroes'` is the name of the route to the `HeroesComponent`. Looking back at the route configuration, we confirm that `'/heroes'` is the path of the route to the `HeroesComponent`.
.l-sub-section .l-sub-section
:marked :marked
Learn about the *link parameters array* in the [Routing](../guide/router-deprecated.html#link-parameters-array) chapter. Learn about the *link parameters array* in the [Routing](../guide/router.html#link-parameters-array) chapter.
:marked :marked
Refresh the browser. We see only the app title. We don't see the heroes list. Refresh the browser. We see only the app title. We don't see the heroes list.
.l-sub-section .l-sub-section
:marked :marked
The browser's address bar shows `/`. The browser's address bar shows `/`.
The route path to `HeroesComponent` is `/heroes`, not `/`. The route path to `HeroesComponent` is `/heroes`, not `/`.
We don't have a route that matches the path `/`, so there is nothing to show. We don't have a route that matches the path `/`, so there is nothing to show.
That's something we'll want to fix. That's something we'll want to fix.
:marked :marked
We click the "Heroes" navigation link, the browser bar updates to `/heroes`, 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! and now we see the list of heroes. We are navigating at last!
At this stage, our `AppComponent` looks like this. At this stage, our `AppComponent` looks like this.
@ -238,73 +233,77 @@ code-example(language="bash").
:marked :marked
## Add a *Dashboard* ## Add a *Dashboard*
Routing only makes sense when we have multiple views. We need another view. 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. Create a placeholder `DashboardComponent` that gives us something to navigate to and from.
+makeExample('toh-5/ts/app/dashboard.component.1.ts',null, 'app/dashboard.component.ts (v1)')(format=".") +makeExample('toh-5/ts/app/dashboard.component.1.ts',null, 'app/dashboard.component.ts (v1)')(format=".")
:marked :marked
Well come back and make it more useful later. Well come back and make it more useful later.
### Configure the dashboard route ### Configure the dashboard route
Go back to `app.component.ts` and teach it to navigate to the dashboard. Go back to `app.routes.ts` and teach it to navigate to the dashboard.
Import the `DashboardComponent` so we can reference it in the dashboard route definition. Import the `DashboardComponent` so we can reference it in the dashboard route definition.
Add the following `'Dashboard'` route definition to the `@RouteConfig` array of definitions. Add the following `'Dashboard'` route definition to the `RouterConfig` array of definitions.
+makeExample('toh-5/ts/app/app.component.ts','dashboard-route', 'app/app.component.ts (Dashboard route)')(format=".") +makeExample('toh-5/ts/app/app.routes.1.ts','dashboard-route', 'app/app.routes.ts (Dashboard route)')(format=".")
.l-sub-section .l-sub-section
:marked :marked
**useAsDefault** **Redirect**
We want the app to show the dashboard when it starts and 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`. 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. Remember that the browser launches with `/` in the address bar.
We don't have a route for that path and we'd rather not create one. We can use a redirect route to make this happen.
Fortunately we can add the `useAsDefault: true` property to the *route definition* and the +makeExample('toh-5/ts/app/app.routes.1.ts','redirect-route', 'app/app.routes.ts (Redirect route)')(format=".")
router will display the dashboard when the browser URL doesn't match an existing route.
.l-sub-section
:marked
Learn about the *redirects* in the [Routing](../guide/router.html#!#redirect) chapter.
:marked :marked
Finally, add a dashboard navigation link to the template, just above the *Heroes* link. Finally, add a dashboard navigation link to the template, just above the *Heroes* link.
+makeExample('toh-5/ts/app/app.component.ts','template', 'app/app.component.ts (template)')(format=".") +makeExample('toh-5/ts/app/app.component.ts','template', 'app/app.component.ts (template)')(format=".")
.l-sub-section .l-sub-section
:marked :marked
We nestled the two links within `<nav>` tags. We nestled the two links within `<nav>` tags.
They don't do anything yet but they'll be convenient when we style the links a little later in the chapter. They don't do anything yet but they'll be convenient when we style the links a little later in the chapter.
:marked :marked
Refresh the browser. The app displays the dashboard and Refresh the browser. The app displays the dashboard and
we can navigate between the dashboard and the heroes. we can navigate between the dashboard and the heroes.
## Dashboard Top Heroes ## Dashboard Top Heroes
Lets spice up the dashboard by displaying the top four heroes at a glance. Lets spice up the dashboard by displaying the top four heroes at a glance.
Replace the `template` metadata with a `templateUrl` property that points to a new Replace the `template` metadata with a `templateUrl` property that points to a new
template file. template file.
+makeExample('toh-5/ts/app/dashboard.component.ts', 'template-url', 'app/dashboard.component.ts (templateUrl)')(format=".") +makeExample('toh-5/ts/app/dashboard.component.ts', 'template-url', 'app/dashboard.component.ts (templateUrl)')(format=".")
.l-sub-section .l-sub-section
:marked :marked
We specify the path _all the way back to the application root_ &mdash; `app/` in this case &mdash; We specify the path _all the way back to the application root_ &mdash; `app/` in this case &mdash;
because Angular doesn't support relative paths _by default_. because Angular doesn't support relative paths _by default_.
We _can_ switch to [component-relative paths](../cookbook/component-relative-paths.html) if we prefer. We _can_ switch to [component-relative paths](../cookbook/component-relative-paths.html) if we prefer.
:marked :marked
Create that file with these contents: Create that file with these contents:
+makeExample('toh-5/ts/app/dashboard.component.html', null, 'app/dashboard.component.html')(format=".") +makeExample('toh-5/ts/app/dashboard.component.html', null, 'app/dashboard.component.html')(format=".")
:marked :marked
We use `*ngFor` once again to iterate over a list of heroes and display their names. We use `*ngFor` once again to iterate over a list of heroes and display their names.
We added extra `<div>` elements to help with styling later in this chapter. We added extra `<div>` elements to help with styling later in this chapter.
There's a `(click)` binding to a `gotoDetail` method we haven't written yet and There's a `(click)` binding to a `gotoDetail` method we haven't written yet and
we're displaying a list of heroes that we don't have. we're displaying a list of heroes that we don't have.
We have work to do, starting with those heroes. We have work to do, starting with those heroes.
### Share the *HeroService* ### Share the *HeroService*
We'd like to re-use the `HeroService` to populate the component's `heroes` array. We'd like to re-use the `HeroService` to populate the component's `heroes` array.
Recall earlier in the chapter that we removed the `HeroService` from the `providers` array of the `HeroesComponent` Recall earlier in the chapter that we removed the `HeroService` from the `providers` array of the `HeroesComponent`
and added it to the `providers` array of the top level `AppComponent`. and added it to the `providers` array of the top level `AppComponent`.
That move created a singleton `HeroService` instance, available to *all* components of the application. That move created a singleton `HeroService` instance, available to *all* components of the application.
Angular will inject `HeroService` and we'll use it here in the `DashboardComponent`. Angular will inject `HeroService` and we'll use it here in the `DashboardComponent`.
### Get heroes ### Get heroes
@ -321,13 +320,13 @@ code-example(language="bash").
* create a `heroes` array property * create a `heroes` array property
* inject the `HeroService` in the constructor and hold it in a private `heroService` field. * inject the `HeroService` in the constructor and hold it in a private `heroService` field.
* call the service to get heroes inside the Angular `ngOnInit` lifecycle hook. * call the service to get heroes inside the Angular `ngOnInit` lifecycle hook.
The noteworthy differences: we cherry-pick four heroes (2nd, 3rd, 4th, and 5th) with *slice* The noteworthy differences: we cherry-pick four heroes (2nd, 3rd, 4th, and 5th) with *slice*
and stub the `gotoDetail` method until we're ready to implement it. and stub the `gotoDetail` method until we're ready to implement it.
Refresh the browser and see four heroes in the new dashboard. Refresh the browser and see four heroes in the new dashboard.
.l-main-section .l-main-section
:marked :marked
## Navigate to Hero Details ## Navigate to Hero Details
@ -336,23 +335,23 @@ code-example(language="bash").
1. from the *Dashboard* to a selected hero. 1. from the *Dashboard* to a selected hero.
1. from the *Heroes* list to a selected hero. 1. from the *Heroes* list to a selected hero.
1. from a "deep link" URL pasted into the browser address bar. 1. from a "deep link" URL pasted into the browser address bar.
Adding a `'HeroDetail'` route seem an obvious place to start. Adding a `'HeroDetail'` route seem an obvious place to start.
### Routing to a hero detail ### Routing to a hero detail
We'll add a route to the `HeroDetailComponent` in the `AppComponent` where our other routes are configured. We'll add a route to the `HeroDetailComponent` in the `AppComponent` where our other routes are configured.
The new route is a bit unusual in that we must tell the `HeroDetailComponent` *which hero to show*. The new route is a bit unusual in that we must tell the `HeroDetailComponent` *which hero to show*.
We didn't have to tell the `HeroesComponent` or the `DashboardComponent` anything. We didn't have to tell the `HeroesComponent` or the `DashboardComponent` anything.
At the moment the parent `HeroesComponent` sets the component's `hero` property to a hero object with a binding like this. At the moment the parent `HeroesComponent` sets the component's `hero` property to a hero object with a binding like this.
code-example(format=''). code-example(format='').
&lt;my-hero-detail [hero]="selectedHero">&lt;/my-hero-detail> &lt;my-hero-detail [hero]="selectedHero">&lt;/my-hero-detail>
:marked :marked
That clearly won't work in any of our routing scenarios. That clearly won't work in any of our routing scenarios.
Certainly not the last one; we can't embed an entire hero object in the URL! Nor would we want to. Certainly not the last one; we can't embed an entire hero object in the URL! Nor would we want to.
### Parameterized route ### Parameterized route
We *can* add the hero's `id` to the URL. When routing to the hero whose `id` is 11, we could expect to see an URL such as this: We *can* add the hero's `id` to the URL. When routing to the hero whose `id` is 11, we could expect to see an URL such as this:
code-example(format=''). code-example(format='').
@ -360,93 +359,99 @@ code-example(format='').
:marked :marked
The `/detail/` part of that URL is constant. The trailing numeric `id` part changes from hero to hero. The `/detail/` part of that URL is constant. The trailing numeric `id` part changes from hero to hero.
We need to represent that variable part of the route with a *parameter* (or *token*) that stands for the hero's `id`. We need to represent that variable part of the route with a *parameter* (or *token*) that stands for the hero's `id`.
### Configure a Route with a Parameter ### Configure a Route with a Parameter
Here's the *route definition* we'll use. Here's the *route definition* we'll use.
+makeExample('toh-5/ts/app/app.component.ts','hero-detail-route', 'app/app.component.ts (route to HeroDetailComponent)')(format=".") +makeExample('toh-5/ts/app/app.routes.1.ts','hero-detail-route', 'app/app.routes.ts (route to HeroDetailComponent)')(format=".")
:marked :marked
The colon (:) in the path indicates that `:id` is a placeholder to be filled with a specific hero `id` The colon (:) in the path indicates that `:id` is a placeholder to be filled with a specific hero `id`
when navigating to the `HeroDetailComponent`. when navigating to the `HeroDetailComponent`.
.l-sub-section .l-sub-section
:marked :marked
Of course we have to import the `HeroDetailComponent` before we create this route: Of course we have to import the `HeroDetailComponent` before we create this route:
+makeExample('toh-5/ts/app/app.component.ts','hero-detail-import')(format=".") +makeExample('toh-5/ts/app/app.routes.1.ts','hero-detail-import')(format=".")
:marked :marked
We're finished with the `AppComponent`. We're finished with the application routes.
We won't add a `'Hero Detail'` link to the template because users We won't add a `'Hero Detail'` link to the template because users
don't click a navigation *link* to view a particular hero. don't click a navigation *link* to view a particular hero.
They click a *hero* whether that hero is displayed on the dashboard or in the heroes list. They click a *hero* whether that hero is displayed on the dashboard or in the heroes list.
We'll get to those *hero* clicks later in the chapter. We'll get to those *hero* clicks later in the chapter.
There's no point in working on them until the `HeroDetailComponent` There's no point in working on them until the `HeroDetailComponent`
is ready to be navigated *to*. is ready to be navigated *to*.
That will require an `HeroDetailComponent` overhaul. That will require an `HeroDetailComponent` overhaul.
.l-main-section .l-main-section
:marked :marked
## Revise the *HeroDetailComponent* ## Revise the *HeroDetailComponent*
Before we rewrite the `HeroDetailComponent`, let's review what it looks like now: Before we rewrite the `HeroDetailComponent`, let's review what it looks like now:
+makeExample('toh-4/ts/app/hero-detail.component.ts', null, 'app/hero-detail.component.ts (current)') +makeExample('toh-4/ts/app/hero-detail.component.ts', null, 'app/hero-detail.component.ts (current)')
:marked :marked
The template won't change. We'll display a hero the same way. The big changes are driven by how we get the hero. The template won't change. We'll display a hero the same way. The big changes are driven by how we get the hero.
We will no longer receive the hero in a parent component property binding.
The new `HeroDetailComponent` should take the `id` parameter from the router's `RouteParams` service
and use the `HeroService` to fetch the hero with that `id`.
We need an import statement to reference the `RouteParams`. We will no longer receive the hero in a parent component property binding.
+makeExample('toh-5/ts/app/hero-detail.component.ts', 'import-route-params')(format=".") The new `HeroDetailComponent` should take the `id` parameter from the `params` observable
in the `ActivatedRoute` service and use the `HeroService` to fetch the hero with that `id`.
We need an import statement to reference the `ActivatedRoute`.
+makeExample('toh-5/ts/app/hero-detail.component.ts', 'import-activated-route')(format=".")
:marked :marked
We import the `HeroService`so we can fetch a hero. We import the `HeroService`so we can fetch a hero.
+makeExample('toh-5/ts/app/hero-detail.component.ts', 'import-hero-service')(format=".") +makeExample('toh-5/ts/app/hero-detail.component.ts', 'import-hero-service')(format=".")
:marked :marked
We import the `OnInit` interface because we'll call the `HeroService` inside the `ngOnInit` component lifecycle hook. We import the `OnInit` and `OnDestroy` interfaces because we'll call the `HeroService` inside the `ngOnInit` component lifecycle hook
and we'll clean up our `params` subscription in the `ngOnDestroy`.
+makeExample('toh-5/ts/app/hero-detail.component.ts', 'import-oninit')(format=".") +makeExample('toh-5/ts/app/hero-detail.component.ts', 'import-oninit')(format=".")
:marked :marked
We inject the both the `RouteParams` service and the `HeroService` into the constructor as we've done before, We inject the both the `ActivatedRoute` service and the `HeroService` into the constructor as we've done before,
making private variables for both: making private variables for both:
+makeExample('toh-5/ts/app/hero-detail.component.ts', 'ctor', 'app/hero-detail.component.ts (constructor)')(format=".") +makeExample('toh-5/ts/app/hero-detail.component.ts', 'ctor', 'app/hero-detail.component.ts (constructor)')(format=".")
:marked :marked
We tell the class that we want to implement the `OnInit` interface. We tell the class that we want to implement the `OnInit` and `OnDestroy` interfaces.
+makeExample('toh-5/ts/app/hero-detail.component.ts', 'implement')(format=".") +makeExample('toh-5/ts/app/hero-detail.component.ts', 'implement')(format=".")
:marked :marked
Inside the `ngOnInit` lifecycle hook, extract the `id` parameter value from the `RouteParams` service Inside the `ngOnInit` lifecycle hook, we _subscribe_ to the `params` observable to
extract the `id` parameter value from the `ActivateRoute` service
and use the `HeroService` to fetch the hero with that `id`. and use the `HeroService` to fetch the hero with that `id`.
+makeExample('toh-5/ts/app/hero-detail.component.ts', 'ng-oninit', 'app/hero-detail.component.ts (ngOnInit)')(format=".") +makeExample('toh-5/ts/app/hero-detail.component.ts', 'ng-oninit', 'app/hero-detail.component.ts (ngOnInit)')(format=".")
:marked :marked
Notice how we extract the `id` by calling the `RouteParams.get` method. Inside the `ngOnDestroy` lifecycle hook, we _unsubscribe_ from the `params` subscription.
+makeExample('toh-5/ts/app/hero-detail.component.ts', 'ng-ondestroy', 'app/hero-detail.component.ts (ngOnDestroy)')(format=".")
:marked
Notice how we extract the `id` by calling the `subscribe` method
which will deliver our array of route parameters.
+makeExample('toh-5/ts/app/hero-detail.component.ts', 'get-id')(format=".") +makeExample('toh-5/ts/app/hero-detail.component.ts', 'get-id')(format=".")
:marked :marked
The hero `id` is a number. Route parameters are *always strings*. The hero `id` is a number. Route parameters are *always strings*.
So we convert the route parameter value to a number with the JavaScript (+) operator. So we convert the route parameter value to a number with the JavaScript (+) operator.
### Add *HeroService.getHero* ### Add *HeroService.getHero*
The problem with this bit of code is that `HeroService` doesn't have a `getHero` method! The problem with this bit of code is that `HeroService` doesn't have a `getHero` method!
We better fix that quickly before someone notices that we broke the app. We better fix that quickly before someone notices that we broke the app.
Open `HeroService` and add a `getHero` method that filters the heroes list from `getHeroes` by `id`: Open `HeroService` and add a `getHero` method that filters the heroes list from `getHeroes` by `id`:
+makeExample('toh-5/ts/app/hero.service.ts', 'get-hero', 'app/hero.service.ts (getHero)')(format=".") +makeExample('toh-5/ts/app/hero.service.ts', 'get-hero', 'app/hero.service.ts (getHero)')(format=".")
:marked :marked
Return to the `HeroDetailComponent` to clean up loose ends. Return to the `HeroDetailComponent` to clean up loose ends.
### Find our way back ### Find our way back
We can navigate *to* the `HeroDetailComponent` in several ways. We can navigate *to* the `HeroDetailComponent` in several ways.
How do we navigate somewhere else when we're done? How do we navigate somewhere else when we're done?
The user could click one of the two links in the `AppComponent`. Or click the browser's back button. The user could click one of the two links in the `AppComponent`. Or click the browser's back button.
We'll add a third option, a `goBack` method that navigates backward one step in the browser's history stack We'll add a third option, a `goBack` method that navigates backward one step in the browser's history stack
+makeExample('toh-5/ts/app/hero-detail.component.ts', 'go-back', 'app/hero-detail.component.ts (goBack)')(format=".") +makeExample('toh-5/ts/app/hero-detail.component.ts', 'go-back', 'app/hero-detail.component.ts (goBack)')(format=".")
.l-sub-section .l-sub-section
:marked :marked
Going back too far could take us out of the application. Going back too far could take us out of the application.
That's acceptable in a demo. We'd guard against it in a real application, That's acceptable in a demo. We'd guard against it in a real application,
perhaps with the [*routerCanDeactivate* hook](../api/router/CanDeactivate-interface.html). perhaps with the [*CanDeactivate* guard](../api/router/index/CanDeactivate-interface.html).
:marked :marked
Then we wire this method with an event binding to a *Back* button that we add to the bottom of the component template. Then we wire this method with an event binding to a *Back* button that we add to the bottom of the component template.
+makeExample('toh-5/ts/app/hero-detail.component.html', 'back-button')(format=".") +makeExample('toh-5/ts/app/hero-detail.component.html', 'back-button')(format=".")
@ -465,28 +470,28 @@ code-example(format='').
:marked :marked
## Select a *Dashboard* Hero ## Select a *Dashboard* Hero
When a user selects a hero in the dashboard, the app should navigate to the `HeroDetailComponent` to view and edit the selected hero. When a user selects a hero in the dashboard, the app should navigate to the `HeroDetailComponent` to view and edit the selected hero.
In the dashboard template we bound each hero's click event to the `gotoDetail` method, passing along the selected `hero` entity. In the dashboard template we bound each hero's click event to the `gotoDetail` method, passing along the selected `hero` entity.
+makeExample('toh-5/ts/app/dashboard.component.html','click', 'app/dashboard.component.html (click binding)')(format=".") +makeExample('toh-5/ts/app/dashboard.component.html','click', 'app/dashboard.component.html (click binding)')(format=".")
:marked :marked
We stubbed the `gotoDetail` method when we rewrote the `DashboardComponent`. We stubbed the `gotoDetail` method when we rewrote the `DashboardComponent`.
Now we give it a real implementation. Now we give it a real implementation.
+makeExample('toh-5/ts/app/dashboard.component.ts','goto-detail', 'app/dashboard.component.ts (gotoDetail)')(format=".") +makeExample('toh-5/ts/app/dashboard.component.ts','goto-detail', 'app/dashboard.component.ts (gotoDetail)')(format=".")
:marked :marked
The `gotoDetail` method navigates in two steps: The `gotoDetail` method navigates in two steps:
1. set a route *link parameters array* 1. set a route *link parameters array*
1. pass the array to the router's navigate method. 1. pass the array to the router's navigate method.
We wrote *link parameters arrays* in the `AppComponent` for the navigation links. We wrote *link parameters arrays* in the `AppComponent` for the navigation links.
Those arrays had only one element, the name of the destination route. Those arrays had only one element, the path of the destination route.
This array has two elements, the ***name*** of the destination route and a ***route parameter object*** This array has two elements, the ***path*** of the destination route and a ***route parameter***
with an `id` field set to the value of the selected hero's `id`. with an `id` field set to the value of the selected hero's `id`.
The two array items align with the ***name*** and ***:id*** token in the parameterized `HeroDetail` route configuration we added to `AppComponent` earlier in the chapter. The two array items align with the ***path*** and ***:id*** token in the parameterized `HeroDetail` route configuration we added to `app.routes.ts` earlier in the chapter.
+makeExample('toh-5/ts/app/app.component.ts','hero-detail-route', 'app/app.component.ts (hero detail route)')(format=".") +makeExample('toh-5/ts/app/app.routes.1.ts','hero-detail-route', 'app/app.routes.ts (hero detail route)')(format=".")
:marked :marked
The `DashboardComponent` doesn't have the router yet. We obtain it in the usual way: The `DashboardComponent` doesn't have the router yet. We obtain it in the usual way:
import the `router` reference and inject it in the constructor (along with the `HeroService`): import the `router` reference and inject it in the constructor (along with the `HeroService`):
+makeExample('toh-5/ts/app/dashboard.component.ts','import-router', 'app/dashboard.component.ts (excerpts)')(format=".") +makeExample('toh-5/ts/app/dashboard.component.ts','import-router', 'app/dashboard.component.ts (excerpts)')(format=".")
@ -498,31 +503,31 @@ code-example(format='').
:marked :marked
## Select a Hero in the *HeroesComponent* ## Select a Hero in the *HeroesComponent*
We'll do something similar in the `HeroesComponent`. We'll do something similar in the `HeroesComponent`.
That component's current template exhibits a "master/detail" style with the list of heroes That component's current template exhibits a "master/detail" style with the list of heroes
at the top and details of the selected hero below. at the top and details of the selected hero below.
+makeExample('toh-4/ts/app/app.component.ts','template', 'app/heroes.component.ts (current template)')(format=".") +makeExample('toh-4/ts/app/app.component.ts','template', 'app/heroes.component.ts (current template)')(format=".")
:marked :marked
Delete the last line of the template with the `<my-hero-detail>` tags. Delete the last line of the template with the `<my-hero-detail>` tags.
We'll no longer show the full `HeroDetailComponent` here. We'll no longer show the full `HeroDetailComponent` here.
We're going to display the hero detail on its own page and route to it as we did in the dashboard. We're going to display the hero detail on its own page and route to it as we did in the dashboard.
But we'll throw in a small twist for variety. But we'll throw in a small twist for variety.
When the user selects a hero from the list, we *won't* go to the detail page. When the user selects a hero from the list, we *won't* go to the detail page.
We'll show a *mini-detail* on *this* page instead and make the user click a button to navigate to the *full detail *page. We'll show a *mini-detail* on *this* page instead and make the user click a button to navigate to the *full detail *page.
### Add the *mini-detail* ### Add the *mini-detail*
Add the following HTML fragment at the bottom of the template where the `<my-hero-detail>` used to be: Add the following HTML fragment at the bottom of the template where the `<my-hero-detail>` used to be:
+makeExample('toh-5/ts/app/heroes.component.html','mini-detail')(format=".") +makeExample('toh-5/ts/app/heroes.component.html','mini-detail')(format=".")
:marked :marked
After clicking a hero, the user should see something like this below the hero list: After clicking a hero, the user should see something like this below the hero list:
figure.image-display figure.image-display
img(src='/resources/images/devguide/toh/mini-hero-detail.png' alt="Mini Hero Detail" height="70") img(src='/resources/images/devguide/toh/mini-hero-detail.png' alt="Mini Hero Detail" height="70")
:marked :marked
### Format with the *UpperCasePipe* ### Format with the *UpperCasePipe*
Notice that the hero's name is displayed in CAPITAL LETTERS. That's the effect of the `UpperCasePipe` Notice that the hero's name is displayed in CAPITAL LETTERS. That's the effect of the `UpperCasePipe`
that we slipped into the interpolation binding. Look for it right after the pipe operator ( | ). that we slipped into the interpolation binding. Look for it right after the pipe operator ( | ).
+makeExample('toh-5/ts/app/heroes.component.html','pipe')(format=".") +makeExample('toh-5/ts/app/heroes.component.html','pipe')(format=".")
@ -536,17 +541,17 @@ figure.image-display
### Move content out of the component file ### Move content out of the component file
We are not done. We still have to update the component class to support navigation to the We are not done. We still have to update the component class to support navigation to the
`HeroDetailComponent` when the user clicks the *View Details* button. `HeroDetailComponent` when the user clicks the *View Details* button.
This component file is really big. Most of it is either template or CSS styles. This component file is really big. Most of it is either template or CSS styles.
It's difficult to find the component logic amidst the noise of HTML and CSS. It's difficult to find the component logic amidst the noise of HTML and CSS.
Let's migrate the template and the styles to their own files before we make any more changes: Let's migrate the template and the styles to their own files before we make any more changes:
1. *Cut-and-paste* the template contents into a new `heroes.component.html` file. 1. *Cut-and-paste* the template contents into a new `heroes.component.html` file.
1. *Cut-and-paste* the styles contents into a new `heroes.component.css` file. 1. *Cut-and-paste* the styles contents into a new `heroes.component.css` file.
1. *Set* the component metadata's `templateUrl` and `styleUrls` properties to refer to both files. 1. *Set* the component metadata's `templateUrl` and `styleUrls` properties to refer to both files.
Because the template for `HeroesComponent` no longer uses `HeroDetailComponent` Because the template for `HeroesComponent` no longer uses `HeroDetailComponent`
directly &mdash; instead using the router to _navigate_ to it &mdash; we can directly &mdash; instead using the router to _navigate_ to it &mdash; we can
remove `HeroDetailComponent` from the directives list. That remove `HeroDetailComponent` from the directives list. That
list is now empty, so we can remove the `directives` property. The revised list is now empty, so we can remove the `directives` property. The revised
`@Component` looks like this: `@Component` looks like this:
@ -556,17 +561,17 @@ figure.image-display
Now we can see what's going on as we update the component class along the same lines as the dashboard: Now we can see what's going on as we update the component class along the same lines as the dashboard:
1. Import the `router` 1. Import the `router`
1. Inject the `router` in the constructor (along with the `HeroService`) 1. Inject the `router` in the constructor (along with the `HeroService`)
1. Implement the `gotoDetail` method by calling the `router.navigate` method 1. Implement the `gotoDetail` method by calling the `router.navigate` method
with a two-part `HeroDetail` *link parameters array*. with a two-part `HeroDetail` *link parameters array*.
Here's the revised component class: Here's the revised component class:
+makeExample('toh-5/ts/app/heroes.component.ts', 'class', 'app/heroes.component.ts (class)') +makeExample('toh-5/ts/app/heroes.component.ts', 'class', 'app/heroes.component.ts (class)')
:marked :marked
Refresh the browser and start clicking. Refresh the browser and start clicking.
We can navigate around the app, from the dashboard to hero details and back, We can navigate around the app, from the dashboard to hero details and back,
for heroes list to the mini-detail to the hero details and back to the heroes again. for heroes list to the mini-detail to the hero details and back to the heroes again.
We can jump back and forth between the dashboard and the heroes. We can jump back and forth between the dashboard and the heroes.
We've met all of the navigational requirements that propelled this chapter. We've met all of the navigational requirements that propelled this chapter.
.l-main-section .l-main-section
@ -576,14 +581,14 @@ figure.image-display
Our creative designer team provided some CSS files to make it look better. Our creative designer team provided some CSS files to make it look better.
### A Dashboard with Style ### A Dashboard with Style
The designers think we should display the dashboard heroes in a row of rectangles. The designers think we should display the dashboard heroes in a row of rectangles.
They've given us ~60 lines of CSS for this purpose including some simple media queries for responsive design. They've given us ~60 lines of CSS for this purpose including some simple media queries for responsive design.
If we paste these ~60 lines into the component `styles` metadata, If we paste these ~60 lines into the component `styles` metadata,
they'll completely obscure the component logic. they'll completely obscure the component logic.
Let's not do that. It's easier to edit CSS in a separate `*.css` file anyway. Let's not do that. It's easier to edit CSS in a separate `*.css` file anyway.
Add a `dashboard.component.css` file to the `app` folder and reference Add a `dashboard.component.css` file to the `app` folder and reference
that file in the component metadata's `styleUrls` array property like this: that file in the component metadata's `styleUrls` array property like this:
+makeExample('toh-5/ts/app/dashboard.component.ts', 'css', 'app/dashboard.component.ts (styleUrls)')(format=".") +makeExample('toh-5/ts/app/dashboard.component.ts', 'css', 'app/dashboard.component.ts (styleUrls)')(format=".")
:marked :marked
@ -595,11 +600,11 @@ figure.image-display
:marked :marked
### Stylish Hero Details ### Stylish Hero Details
The designers also gave us CSS styles specifically for the `HeroDetailComponent`. The designers also gave us CSS styles specifically for the `HeroDetailComponent`.
Add a `hero-detail.component.css` to the `app` folder and refer to that file inside Add a `hero-detail.component.css` to the `app` folder and refer to that file inside
the `styleUrls` array as we did for `DashboardComponent`. the `styleUrls` array as we did for `DashboardComponent`.
Here's the content for the aforementioned component CSS files. Here's the content for the aforementioned component CSS files.
+makeTabs( +makeTabs(
`toh-5/ts/app/hero-detail.component.css, `toh-5/ts/app/hero-detail.component.css,
toh-5/ts/app/dashboard.component.css`, toh-5/ts/app/dashboard.component.css`,
@ -610,29 +615,31 @@ figure.image-display
### Style the Navigation Links ### Style the Navigation Links
The designers gave us CSS to make the navigation links in our `AppComponent` look more like selectable buttons. The designers gave us CSS to make the navigation links in our `AppComponent` look more like selectable buttons.
We cooperated by surrounding those links in `<nav>` tags. We cooperated by surrounding those links in `<nav>` tags.
Add a `app.component.css` file to the `app` folder with the following content. Add a `app.component.css` file to the `app` folder with the following content.
+makeExample('toh-5/ts/app/app.component.css', '', 'app/app.component.css (navigation styles)') +makeExample('toh-5/ts/app/app.component.css', '', 'app/app.component.css (navigation styles)')
.l-sub-section .l-sub-section
:marked :marked
**The *router-link-active* class** **The *routerLinkActive* directive**
The Angular Router adds the `router-link-active` class to the HTML navigation element The Angular Router provides a `routerLinkActive` directive we can use to
whose route matches the active route. All we have to do is define the style for it. Sweet! to add a class to the HTML navigation element whose route matches the active route.
All we have to do is define the style for it. Sweet!
+makeExample('toh-5/ts/app/app.component.3.ts', 'router-link-active', 'app/app.component.ts (active router links)')(format=".")
:marked :marked
Set the `AppComponent`s `styleUrls` property to this CSS file. Set the `AppComponent`s `styleUrls` property to this CSS file.
+makeExample('toh-5/ts/app/app.component.ts','style-urls', 'app/app.component.ts (styleUrls)')(format=".") +makeExample('toh-5/ts/app/app.component.ts','style-urls', 'app/app.component.ts (styleUrls)')(format=".")
:marked :marked
### Global application styles ### Global application styles
When we add styles to a component, we're keeping everything a component needs When we add styles to a component, we're keeping everything a component needs
&mdash; HTML, the CSS, the code &mdash; together in one convenient place. &mdash; HTML, the CSS, the code &mdash; together in one convenient place.
It's pretty easy to package it all up and re-use the component somewhere else. It's pretty easy to package it all up and re-use the component somewhere else.
We can also create styles at the *application level* outside of any component. We can also create styles at the *application level* outside of any component.
Our designers provided some basic styles to apply to elements across the entire app. Our designers provided some basic styles to apply to elements across the entire app.
These correspond to the full set of master styles that we These correspond to the full set of master styles that we
introduced earlier (see introduced earlier (see
[QuickStart, "Add some style"](../quickstart.html#!#add-some-style)). [QuickStart, "Add some style"](../quickstart.html#!#add-some-style)).
Here is an excerpt. Here is an excerpt.
@ -648,7 +655,7 @@ figure.image-display
+makeExample('toh-5/ts/index.html','css', 'index.html (link ref)')(format=".") +makeExample('toh-5/ts/index.html','css', 'index.html (link ref)')(format=".")
:marked :marked
Look at the app now. Our dashboard, heroes, and navigation links are styling! Look at the app now. Our dashboard, heroes, and navigation links are styling!
figure.image-display figure.image-display
img(src='/resources/images/devguide/toh/dashboard-top-heroes.png' alt="View navigations") img(src='/resources/images/devguide/toh/dashboard-top-heroes.png' alt="View navigations")
@ -667,6 +674,7 @@ p.
.children .children
.file app.component.ts .file app.component.ts
.file app.component.css .file app.component.css
.file app.routes.ts
.file dashboard.component.css .file dashboard.component.css
.file dashboard.component.html .file dashboard.component.html
.file dashboard.component.ts .file dashboard.component.ts
@ -681,7 +689,7 @@ p.
.file main.ts .file main.ts
.file mock-heroes.ts .file mock-heroes.ts
.file node_modules ... .file node_modules ...
.file typings ... .file typings ...
.file index.html .file index.html
.file package.json .file package.json
.file styles.css .file styles.css
@ -704,7 +712,7 @@ p.
### The Road Ahead ### The Road Ahead
We have much of the foundation we need to build an application. We have much of the foundation we need to build an application.
We're still missing a key piece: remote data access. We're still missing a key piece: remote data access.
In the next chapter, In the next chapter,
well replace our mock data with data retrieved from a server using http. well replace our mock data with data retrieved from a server using http.