docs(toh-5): TS/Dart review, and Dart resync (#2115)

* docs(toh-5): review and update/resync Dart

**NOTE: run `gulp add-example-boilerplate` after pulling in the
commit.**

This is preparatory work for #2035.
As part of the the chapter review, the Dart .jade was enhanced to use
Jade extends (#2018).
By the same token it contributed to a post-RC5 resync (#2077). Other
key changes:

Dart and TS code:
- Eliminated `styles.1.css` in favor of docregions in `styles.css`.
- `docregion` tags renamed in a few places.
- **No other code changes**.

TS prose
- Fixed: misnamed variable `routing` -> `appRoutes`.
- All other changes are **minor copy edits**, or changes to support
Dart via Jade extends.

Diff of generated HTML for TS chapter was inspected to ensure only
minor copy edits prevailed (i.e., that the support for Jade extends had
no impact on the generated HTML).

* docs(toh-5): edits after doing tutorial

- Some adjustments following actually doing the tutorial. In some cases code shown (e.g. this is what file foo should look like now) didn't match what the user would have. E.g., lingering @Input on the hero property.
- Fixed some lingering deprecated-router prose elements on TS side (e.g., still referring to a route by the old string names like `HeroDetail`).
- Added extra step to `app.component.ts` creation rather than having a critical-call-out later on.
- Reorder some prose for better harmony between TS and Dart prose (also improves the flow).
- Moved the `styleUrls` call-out to the point of first use.

* post-review changes

* more post-review changes

* toh-6 cache update
This commit is contained in:
Patrice Chalin 2016-08-17 13:31:40 -07:00 committed by Kathy Walrath
parent 9869bf585d
commit 0c0c6f69f3
32 changed files with 1260 additions and 1585 deletions

View File

@ -222,8 +222,8 @@ script.
- // E.g. of a project relative path is 'app/main.ts'
- if (ex.title === null || ex.title === undefined) {
- // Title is not given so take it to be ex.filePath.
- // Is title like styles.1.css? Then drop the '.1' qualifier:
- var matches = ex.filePath.match(/^(.*)\.\d(\.\w+)$/);
- // Title like styles.1.css or foo_1.dart? Then drop the '.1' or '_1' qualifier:
- var matches = ex.filePath.match(/^(.*)[\._]\d(\.\w+)$/);
- ex.title = matches ? matches[1] + matches[2] : ex.filePath;
- }
- ex.filePath = getExampleName() + '/' + _docsFor + '/' + ex.filePath;

View File

@ -1,4 +1,4 @@
/* #docregion , quickstart */
/* #docregion , quickstart, toh */
/* Master Styles */
h1 {
color: #369;
@ -18,6 +18,7 @@ body, input[text], button {
color: #888;
font-family: Cambria, Georgia;
}
/* #enddocregion toh */
a {
cursor: pointer;
cursor: hand;
@ -137,7 +138,7 @@ nav a.active {
margin-right: .8em;
border-radius: 4px 0 0 4px;
}
/* #docregion toh */
/* everywhere else */
* {
font-family: Arial, Helvetica, sans-serif;

View File

@ -1,18 +1,18 @@
// #docplaster
// #docregion
import 'package:angular2/core.dart';
// #docregion import-router
import 'package:angular2/router.dart';
// #enddocregion import-router
import 'package:angular2_tour_of_heroes/heroes_component.dart';
import 'package:angular2_tour_of_heroes/hero_service.dart';
import 'package:angular2_tour_of_heroes/dashboard_component.dart';
// #docregion hero-detail-import
import 'package:angular2_tour_of_heroes/hero_detail_component.dart';
// #enddocregion hero-detail-import
import 'dashboard_component.dart';
import 'hero_detail_component.dart';
import 'hero_service.dart';
import 'heroes_component.dart';
@Component(
selector: 'my-app',
// #docregion template
// #docregion template, template-v3
template: '''
<h1>{{title}}</h1>
<nav>
@ -20,26 +20,32 @@ import 'package:angular2_tour_of_heroes/hero_detail_component.dart';
<a [routerLink]="['Heroes']">Heroes</a>
</nav>
<router-outlet></router-outlet>''',
// #enddocregion template
// #docregion style-urls
// #enddocregion template, template-v3
// #docregion styleUrls
styleUrls: const ['app_component.css'],
// #enddocregion style-urls
// #enddocregion styleUrls
// #docregion directives-and-providers
directives: const [ROUTER_DIRECTIVES],
providers: const [HeroService, ROUTER_PROVIDERS])
// #enddocregion directives-and-providers
// #docregion heroes
@RouteConfig(const [
// #docregion dashboard-route
// #enddocregion heroes
// #docregion dashboard
const Route(
path: '/dashboard',
name: 'Dashboard',
component: DashboardComponent,
useAsDefault: true),
// #enddocregion dashboard-route
// #docregion hero-detail-route
// #enddocregion dashboard
// #docregion hero-detail
const Route(
path: '/detail/:id', name: 'HeroDetail', component: HeroDetailComponent),
// #enddocregion hero-detail-route
// #enddocregion hero-detail
// #docregion heroes
const Route(path: '/heroes', name: 'Heroes', component: HeroesComponent)
])
// #enddocregion heroes
class AppComponent {
String title = 'Tour of Heroes';
}

View File

@ -1,25 +1,40 @@
// #docplaster
// #docregion
// #docregion , v2
import 'package:angular2/core.dart';
// #enddocregion
import 'package:angular2/router.dart'; // for testing only
// #enddocregion ,
// #docregion v2
import 'package:angular2/router.dart';
// #docregion
import 'hero_service.dart';
import 'heroes_component.dart';
// #enddocregion v2
@Component(
selector: 'my-app',
template: '''
<h1>{{title}}</h1>
<my-heroes></my-heroes>''',
directives: const [HeroesComponent],
providers: const [
// #enddocregion
ROUTER_PROVIDERS,
// #docregion
HeroService
])
providers: const [HeroService])
// #enddocregion ,
class Bogus {}
// #docregion v2
@Component(
selector: 'my-app',
// #docregion template-v2
template: '''
<h1>{{title}}</h1>
<a [routerLink]="['Heroes']">Heroes</a>
<router-outlet></router-outlet>''',
// #enddocregion template-v2
directives: const [ROUTER_DIRECTIVES],
providers: const [HeroService, ROUTER_PROVIDERS])
@RouteConfig(const [
const Route(path: '/heroes', name: 'Heroes', component: HeroesComponent)
])
// #docregion ,
class AppComponent {
String title = 'Tour of Heroes';
}

View File

@ -1,31 +0,0 @@
// #docplaster
// #docregion
import 'package:angular2/core.dart';
// #docregion import-router
import 'package:angular2/router.dart';
// #enddocregion import-router
import 'hero_service.dart';
import 'heroes_component.dart';
@Component(
selector: 'my-app',
// #docregion template
template: '''
<h1>{{title}}</h1>
<a [routerLink]="['Heroes']">Heroes</a>
<router-outlet></router-outlet>''',
// #enddocregion template
// #docregion directives-and-providers
directives: const [ROUTER_DIRECTIVES],
providers: const [ROUTER_PROVIDERS, HeroService]
// #enddocregion directives-and-providers
)
// #docregion route-config
@RouteConfig(const [
const Route(path: '/heroes', name: 'Heroes', component: HeroesComponent)
])
// #enddocregion route-config
class AppComponent {
String title = 'Tour of Heroes';
}

View File

@ -12,9 +12,9 @@ import 'hero_service.dart';
@Component(
selector: 'my-dashboard',
// #docregion template-url
// #docregion templateUrl
templateUrl: 'dashboard_component.html',
// #enddocregion template-url
// #enddocregion templateUrl
// #docregion css
styleUrls: const ['dashboard_component.css']
// #enddocregion css
@ -35,7 +35,7 @@ class DashboardComponent implements OnInit {
heroes = (await _heroService.getHeroes()).skip(1).take(4).toList();
}
// #docregion goto-detail
// #docregion gotoDetail
void gotoDetail(Hero hero) {
var link = [
'HeroDetail',
@ -43,5 +43,5 @@ class DashboardComponent implements OnInit {
];
_router.navigate(link);
}
// #enddocregion goto-detail
// #enddocregion gotoDetail
}

View File

@ -22,5 +22,5 @@ class DashboardComponent implements OnInit {
heroes = (await _heroService.getHeroes()).skip(1).take(4).toList();
}
gotoDetail() {/* not implemented yet */}
gotoDetail(Hero hero) {/* not implemented yet */}
}

View File

@ -1,30 +1,28 @@
// #docplaster
// #docregion , v2
// #docregion added-imports
import 'dart:async';
import 'dart:html';
import 'dart:html' show window;
// #docregion import-oninit
// #enddocregion added-imports
import 'package:angular2/core.dart';
// #enddocregion import-oninit
// #docregion import-route-params
// #docregion added-imports
import 'package:angular2/router.dart';
// #enddocregion import-route-params
// #enddocregion added-imports
import 'hero.dart';
// #docregion import-hero-service
// #docregion added-imports
import 'hero_service.dart';
// #enddocregion import-hero-service
// #enddocregion added-imports
// #docregion extract-template
@Component(
selector: 'my-hero-detail',
// #docregion template-url
// #docregion templateUrl
templateUrl: 'hero_detail_component.html',
// #enddocregion template-url, v2
// #enddocregion templateUrl, v2
styleUrls: const ['hero_detail_component.css']
// #docregion v2
)
// #enddocregion extract-template
// #docregion implement
class HeroDetailComponent implements OnInit {
// #enddocregion implement
@ -36,19 +34,17 @@ class HeroDetailComponent implements OnInit {
HeroDetailComponent(this._heroService, this._routeParams);
// #enddocregion ctor
// #docregion ng-oninit
// #docregion ngOnInit
Future<Null> ngOnInit() async {
// #docregion get-id
var idString = _routeParams.get('id');
var id = int.parse(idString, onError: (_) => null);
// #enddocregion get-id
var id = int.parse(idString ?? '', onError: (_) => null);
if (id != null) hero = await (_heroService.getHero(id));
}
// #enddocregion ng-oninit
// #enddocregion ngOnInit
// #docregion go-back
// #docregion goBack
void goBack() {
window.history.back();
}
// #enddocregion go-back
// #enddocregion goBack
}

View File

@ -16,8 +16,8 @@ class HeroService {
const Duration(seconds: 2), () => mockHeroes);
}
// #docregion get-hero
// #docregion getHero
Future<Hero> getHero(int id) async =>
(await getHeroes()).firstWhere((hero) => hero.id == id);
// #enddocregion get-hero
// #enddocregion getHero
}

View File

@ -6,27 +6,28 @@ import 'package:angular2/core.dart';
import 'package:angular2/router.dart';
import 'hero.dart';
import 'hero_detail_component.dart';
import 'hero_service.dart';
// #docregion metadata, heroes-component-renaming
// #docregion metadata, renaming
@Component(
selector: 'my-heroes',
// #enddocregion heroes-component-renaming
// #enddocregion renaming
templateUrl: 'heroes_component.html',
styleUrls: const ['heroes_component.css'],
directives: const [HeroDetailComponent])
// #docregion heroes-component-renaming
// #enddocregion heroes-component-renaming, metadata
// #docregion class, heroes-component-renaming
styleUrls: const ['heroes_component.css']
// #docregion renaming
)
// #enddocregion metadata
// #docregion class
class HeroesComponent implements OnInit {
// #enddocregion heroes-component-renaming
// #enddocregion renaming
final Router _router;
final HeroService _heroService;
List<Hero> heroes;
Hero selectedHero;
// #docregion renaming
HeroesComponent(this._heroService, this._router);
// #enddocregion renaming
Future<Null> getHeroes() async {
heroes = await _heroService.getHeroes();
@ -44,5 +45,5 @@ class HeroesComponent implements OnInit {
'HeroDetail',
{'id': selectedHero.id.toString()}
]);
// #docregion heroes-component-renaming
// #docregion renaming
}

View File

@ -1,24 +0,0 @@
/* #docregion toh-excerpt */
/* Master Styles */
h1 {
color: #369;
font-family: Arial, Helvetica, sans-serif;
font-size: 250%;
}
h2, h3 {
color: #444;
font-family: Arial, Helvetica, sans-serif;
font-weight: lighter;
}
body {
margin: 2em;
}
body, input[text], button {
color: #888;
font-family: Cambria, Georgia;
}
/* . . . */
/* everywhere else */
* {
font-family: Arial, Helvetica, sans-serif;
}

View File

@ -1,7 +1,8 @@
// #docplaster
// #docregion
// #docregion , v2
import { Component } from '@angular/core';
// #enddocregion v2
@Component({
selector: 'my-app',
template: `
@ -9,6 +10,33 @@ import { Component } from '@angular/core';
<my-heroes></my-heroes>
`
})
// #enddocregion
// #docregion v2
@Component({
selector: 'my-app',
// #docregion template-v2
template: `
<h1>{{title}}</h1>
<a routerLink="/heroes">Heroes</a>
<router-outlet></router-outlet>
`
// #enddocregion template-v2
})
// #enddocregion
@Component({
selector: 'my-app',
// #docregion template-v3
template: `
<h1>{{title}}</h1>
<nav>
<a routerLink="/dashboard">Dashboard</a>
<a routerLink="/heroes">Heroes</a>
</nav>
<router-outlet></router-outlet>
`
// #enddocregion template-v3
})
// #docregion , v2
export class AppComponent {
title = 'Tour of Heroes';
}

View File

@ -1,17 +0,0 @@
// #docplaster
// #docregion
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
// #docregion template
template: `
<h1>{{title}}</h1>
<a routerLink="/heroes">Heroes</a>
<router-outlet></router-outlet>
`
// #enddocregion template
})
export class AppComponent {
title = 'Tour of Heroes';
}

View File

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

View File

@ -1,4 +1,3 @@
// #docplaster
// #docregion
import { Component } from '@angular/core';
@ -14,9 +13,9 @@ import { Component } from '@angular/core';
<router-outlet></router-outlet>
`,
// #enddocregion template
// #docregion style-urls
// #docregion styleUrls
styleUrls: ['app/app.component.css'],
// #enddocregion style-urls
// #enddocregion styleUrls
})
export class AppComponent {
title = 'Tour of Heroes';

View File

@ -1,30 +0,0 @@
// #docregion
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { routing } from './app.routing';
import { HeroesComponent } from './heroes.component';
import { HeroService } from './hero.service';
@NgModule({
imports: [
BrowserModule,
FormsModule,
routing
],
declarations: [
AppComponent,
HeroesComponent
],
providers: [
HeroService
],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
// #enddocregion

View File

@ -1,47 +0,0 @@
// #docplaster
// #docregion
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { routing } from './app.routing';
import { HeroesComponent } from './heroes.component';
// #docregion dashboard-declaration
import { DashboardComponent } from './dashboard.component';
// #enddocregion dashboard-declaration
// #docregion hero-detail-declaration
import { HeroDetailComponent } from './hero-detail.component';
// #enddocregion hero-detail-declaration
import { HeroService } from './hero.service';
@NgModule({
imports: [
BrowserModule,
FormsModule,
routing
],
// #docregion dashboard-declaration, hero-detail-declaration
declarations: [
// #enddocregion dashboard-declaration, hero-detail-declaration
AppComponent,
HeroesComponent,
// #docregion dashboard-declaration
DashboardComponent,
// #enddocregion dashboard-declaration
// #docregion hero-detail-declaration
HeroDetailComponent
// #enddocregion hero-detail-declaration
// #docregion dashboard-declaration, hero-detail-declaration
],
// #enddocregion dashboard-declaration, hero-detail-declaration
providers: [
HeroService
],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
// #enddocregion

View File

@ -1,16 +1,20 @@
// #docplaster
// #docregion
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
// #docregion routing
import { routing } from './app.routing';
// #enddocregion routing
import { HeroesComponent } from './heroes.component';
import { DashboardComponent } from './dashboard.component';
import { HeroDetailComponent } from './hero-detail.component';
import { HeroService } from './hero.service';
// #docregion routing
@NgModule({
imports: [
@ -18,17 +22,22 @@ import { HeroService } from './hero.service';
FormsModule,
routing
],
// #enddocregion routing
// #docregion dashboard, hero-detail
declarations: [
AppComponent,
HeroesComponent,
DashboardComponent,
// #enddocregion dashboard
HeroDetailComponent
// #docregion dashboard
],
// #enddocregion dashboard, hero-detail
providers: [
HeroService
],
bootstrap: [ AppComponent ]
// #docregion routing
})
export class AppModule {
}
// #enddocregion

View File

@ -1,5 +1,4 @@
// #docregion
// #docregion routing-config
// #docregion , heroes
import { Routes, RouterModule } from '@angular/router';
import { HeroesComponent } from './heroes.component';
@ -10,8 +9,6 @@ const appRoutes: Routes = [
component: HeroesComponent
}
];
// #enddocregion routing-config
// #enddocregion heroes
// #docregion routing-export
export const routing = RouterModule.forRoot(appRoutes);
// #enddocregion routing-export

View File

@ -1,36 +0,0 @@
// #docregion
import { Routes, RouterModule } 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
const appRoutes: Routes = [
// #docregion redirect-route
{
path: '',
redirectTo: '/dashboard',
pathMatch: 'full'
},
// #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 routing = RouterModule.forRoot(appRoutes);

View File

@ -1,30 +1,43 @@
// #docregion
// #docplaster
// #docregion , heroes
import { Routes, RouterModule } 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
// #enddocregion heroes
import { DashboardComponent } from './dashboard.component';
// #docregion heroes
import { HeroesComponent } from './heroes.component';
// #enddocregion heroes
import { HeroDetailComponent } from './hero-detail.component';
// #docregion heroes
const appRoutes: Routes = [
// #enddocregion heroes
// #docregion redirect
{
path: '',
redirectTo: '/dashboard',
pathMatch: 'full'
},
// #enddocregion redirect
// #docregion dashboard
{
path: 'dashboard',
component: DashboardComponent
},
// #enddocregion dashboard
// #docregion hero-detail
{
path: 'detail/:id',
component: HeroDetailComponent
},
// #enddocregion hero-detail
// #docregion heroes
{
path: 'heroes',
component: HeroesComponent
}
];
// #enddocregion heroes
// #docregion routing
export const routing = RouterModule.forRoot(appRoutes);

View File

@ -22,5 +22,5 @@ export class DashboardComponent implements OnInit {
.then(heroes => this.heroes = heroes.slice(1, 5));
}
gotoDetail() { /* not implemented yet */}
gotoDetail(hero: Hero) { /* not implemented yet */}
}

View File

@ -10,9 +10,9 @@ import { HeroService } from './hero.service';
@Component({
selector: 'my-dashboard',
// #docregion template-url
// #docregion templateUrl
templateUrl: 'app/dashboard.component.html',
// #enddocregion template-url
// #enddocregion templateUrl
// #docregion css
styleUrls: ['app/dashboard.component.css']
// #enddocregion css
@ -34,10 +34,10 @@ export class DashboardComponent implements OnInit {
.then(heroes => this.heroes = heroes.slice(1, 5));
}
// #docregion goto-detail
// #docregion gotoDetail
gotoDetail(hero: Hero) {
let link = ['/detail', hero.id];
this.router.navigate(link);
}
// #enddocregion goto-detail
// #enddocregion gotoDetail
}

View File

@ -0,0 +1,27 @@
// Imports in comments cause problems when the app is executed
// (some error about 'traceur' missing). Hence this separate file
// is solely for containing the transitory state of the imports.
// #docregion added-imports
// Keep the Input import for now, we'll remove it later:
import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { HeroService } from './hero.service';
// #enddocregion added-imports
// Bogus code below this point. It is only here to make lint happy.
import { Hero } from './hero';
@Component({})
export class HeroDetailComponent implements OnInit {
@Input() hero: Hero;
bogus: Params;
constructor(
private heroService: HeroService,
private route: ActivatedRoute) {
}
ngOnInit() {}
}

View File

@ -1,27 +1,19 @@
// #docplaster
// #docregion
// #docregion import-oninit, v2
// #docregion , v2
import { Component, OnInit } from '@angular/core';
// #enddocregion import-oninit
// #docregion import-activated-route
import { ActivatedRoute, Params } from '@angular/router';
// #enddocregion import-activated-route
import { Hero } from './hero';
// #docregion import-hero-service
import { HeroService } from './hero.service';
// #enddocregion import-hero-service
// #docregion extract-template
@Component({
selector: 'my-hero-detail',
// #docregion template-url
// #docregion templateUrl
templateUrl: 'app/hero-detail.component.html',
// #enddocregion template-url, v2
// #enddocregion templateUrl, v2
styleUrls: ['app/hero-detail.component.css']
// #docregion v2
})
// #enddocregion extract-template
// #docregion implement
export class HeroDetailComponent implements OnInit {
// #enddocregion implement
@ -34,21 +26,19 @@ export class HeroDetailComponent implements OnInit {
}
// #enddocregion ctor
// #docregion ng-oninit
// #docregion ngOnInit
ngOnInit() {
// #docregion get-id
this.route.params.forEach((params: Params) => {
let id = +params['id'];
this.heroService.getHero(id)
.then(hero => this.hero = hero);
});
// #enddocregion get-id
}
// #enddocregion ng-oninit
// #enddocregion ngOnInit
// #docregion go-back
// #docregion goBack
goBack() {
window.history.back();
}
// #enddocregion go-back
// #enddocregion goBack
}

View File

@ -17,10 +17,10 @@ export class HeroService {
);
}
// #docregion get-hero
// #docregion getHero
getHero(id: number) {
return this.getHeroes()
.then(heroes => heroes.find(hero => hero.id === id));
}
// #enddocregion get-hero
// #enddocregion getHero
}

View File

@ -6,18 +6,18 @@ import { Router } from '@angular/router';
import { Hero } from './hero';
import { HeroService } from './hero.service';
// #docregion heroes-component-renaming, metadata
// #docregion renaming, metadata
@Component({
selector: 'my-heroes',
// #enddocregion heroes-component-renaming
// #enddocregion renaming
templateUrl: 'app/heroes.component.html',
styleUrls: ['app/heroes.component.css']
// #docregion heroes-component-renaming
// #docregion renaming
})
// #enddocregion heroes-component-renaming, metadata
// #docregion class, heroes-component-renaming
// #enddocregion metadata
// #docregion class
export class HeroesComponent implements OnInit {
// #enddocregion heroes-component-renaming
// #enddocregion renaming
heroes: Hero[];
selectedHero: Hero;
@ -38,5 +38,5 @@ export class HeroesComponent implements OnInit {
gotoDetail() {
this.router.navigate(['/detail', this.selectedHero.id]);
}
// #docregion heroes-component-renaming
// #docregion renaming
}

View File

@ -1,24 +0,0 @@
/* #docregion toh-excerpt */
/* Master Styles */
h1 {
color: #369;
font-family: Arial, Helvetica, sans-serif;
font-size: 250%;
}
h2, h3 {
color: #444;
font-family: Arial, Helvetica, sans-serif;
font-weight: lighter;
}
body {
margin: 2em;
}
body, input[text], button {
color: #888;
font-family: Cambria, Georgia;
}
/* . . . */
/* everywhere else */
* {
font-family: Arial, Helvetica, sans-serif;
}

View File

@ -1,702 +1,168 @@
include ../_util-fns
extends ../../../ts/_cache/tutorial/toh-pt5
: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.
block includes
include ../_util-fns
- var _appRoutingTsVsAppComp = 'AppComponent'
- var _declsVsDirectives = 'directives'
- var _RoutesVsAtRouteConfig = '@RouteConfig'
- var _RouterModuleVsRouterDirectives = 'ROUTER_DIRECTIVES'
- var _redirectTo = 'useAsDefault'
When were 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 Angulars *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.
Run the <live-example></live-example> for this part.
.l-main-section
:marked
## 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
and hero detail component. If not, well need to go back and follow the previous chapters.
.filetree
block intro-file-tree
.filetree
.file angular2_tour_of_heroes
.children
.file lib
.children
.file app_component.dart
.file hero.dart
.file hero_detail_component.dart
.file hero_service.dart
.file mock_heroes.dart
.file web
.children
.file index.html
.file main.dart
.file styles.css
.file pubspec.yaml
:marked
### Keep the app compiling and running
Open a terminal/console window.
Start the Dart compiler, watch for changes, and start our server by entering the command:
.file lib
.children
.file app_component.dart
.file hero.dart
.file hero_detail_component.dart
.file hero_service.dart
.file mock_heroes.dart
.file web
.children
.file index.html
.file main.dart
.file styles.css
.file pubspec.yaml
code-example(language="bash").
pub serve
: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
block keep-app-running
:marked
*Routing* is another name for *navigation*. The *router* is the mechanism for navigating from view to view.
### Keep the app compiling and running
.l-main-section
:marked
## Splitting the *AppComponent*
Open a terminal/console window.
Start the Dart compiler, watch for changes, and start our server by entering the command:
Our current app loads `AppComponent` and immediately displays the list of heroes.
code-example(language="bash").
pub serve
Our revised app should present a shell with a choice of views (*Dashboard* and *Heroes*) and then default to one of them.
block app-comp-v1
+makeExcerpt('lib/app_component_1.dart (v1)', '')
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.dart` file to `heroes_component.dart`
* `AppComponent` class to `HeroesComponent`
* Selector `my-app` to `my-heroes`
:marked
+makeExample('toh-5/dart/lib/heroes_component.dart', 'heroes-component-renaming', 'lib/heroes_component.dart (showing renamings only)')(format=".")
: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 a new file named `app_component.dart`.
* define an `AppComponent` class.
* expose an application `title` property.
* add the `@Component` metadata annotation above the class with a `my-app` selector.
* add a template with `<h1>` tags surrounding a binding to the `title` property.
* add the `<my-heroes>` tags to the template so we still see the heroes.
* add the `HeroesComponent` to the `directives` list so Angular recognizes the `<my-heroes>` tags.
* add the `HeroService` to the `providers` list because we'll need it in every other view.
* add the supporting `import` statements.
Our first draft looks like this:
+makeExample('toh-5/dart/lib/app_component_1.dart', null, 'lib/app_component.dart (v1)')
:marked
.callout.is-critical
header Remove <i>HeroService</i> from the <i>HeroesComponent</i> providers
block angular-router
:marked
Go back to the `HeroesComponent` and **remove the `HeroService`** from its `providers` list.
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.
: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.
The Angular router is a combination of multiple services
(`ROUTER_PROVIDERS`), multiple directives (`ROUTER_DIRECTIVES`), and a
configuration annotation (`RouteConfig`). We'll get them all by importing
the router library:
:marked
## Add Routing
+makeExcerpt('app/app.component.ts (router imports)', 'import-router')
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*.
### Add a base tag
:marked
First, edit `index.html` and add `<base href="/">` at the top of the `<head>` section.
+makeExample('toh-5/dart/web/index.html', 'base-href', 'index.html (base href)')(format=".")
.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.
:marked
### Make the router available
### Make the router available
Not all apps need routing, which is why the Angular *Component Router* is in a separate, optional module library.
Not all apps need routing, which is why the Angular *Component Router* is
in a separate, optional library module.
The Angular router is a combination of multiple services (`ROUTER_PROVIDERS`), multiple directives (`ROUTER_DIRECTIVES`),
and a configuration annotation (`RouteConfig`). We'll get them all by importing `router.dart`:
+makeExample('toh-5/dart/lib/app_component_2.dart', 'import-router', 'lib/app_component.dart (router imports)')(format=".")
Like for any service, we make router services available to the application
by adding them to the `providers` list. Let's update the `directives` and
`providers` lists to include the router assets:
:marked
The *Component Router* is a service. Like any service, we have to make it
available to the application by adding it to the `providers` list.
+makeExcerpt('app/app.component.ts (excerpt)', 'directives-and-providers')
Let's update the `directives` and `providers` metadata lists to *include* the router assets.
+makeExample('toh-5/dart/lib/app_component_2.dart', 'directives-and-providers', 'lib/app_component.dart (directives and providers)')(format=".")
:marked
Notice that we also removed the `HeroesComponent` from the `directives` list.
`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` annotation 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.
Let's define our first route, a route to the `HeroesComponent`.
+makeExample('toh-5/dart/lib/app_component_2.dart', 'route-config', 'lib/app_component.dart (RouteConfig for heroes)')(format=".")
:marked
`@RouteConfig` takes a list of *route definitions*.
We have only one route definition at the moment but rest assured, we'll add more.
This *route definition* has three parts:
* **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`).
.l-sub-section
:marked
Learn more about defining routes with @RouteConfig in the [Routing](../guide/router.html) chapter.
:marked
### Router Outlet
Notice that we also removed the `HeroesComponent` from the `directives` list.
`AppComponent` no longer shows heroes; that will be the router's job.
We'll soon remove `<my-heroes>` from the template too.
If we paste the path, `/heroes`, into the browser address bar,
the router should match it to the `'Heroes'` route and display the `HeroesComponent`.
But where?
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`.
The router displays each component immediately below the `<router-outlet>` 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:
+makeExample('toh-5/dart/lib/app_component_2.dart', 'template', 'lib/app_component.dart (template v1)')(format=".")
:marked
Notice the `[routerLink]` binding in the anchor tag.
We bind the `RouterLink` directive (another of the `ROUTER_DIRECTIVES`) to a list
that tells the router where to navigate when the user clicks the link.
We define a *routing instruction* with a *link parameters list*.
The list only has one element in our little sample, the quoted ***name* of the route** to follow.
Looking back at the route configuration, we confirm that `'Heroes'` is the name of the route to the `HeroesComponent`.
.l-sub-section
block router-config-intro
:marked
Learn about the *link parameters list* in the [Routing](../guide/router.html#link-parameters-array) chapter.
:marked
Refresh the browser. We see only the app title. We don't see the heroes list.
.l-sub-section
### Configure routes and add the router
The `AppComponent` doesn't have a router yet. We'll use the `@RouteConfig`
annotation to simultaneously:
- Assign a router to the component
- Configure that router with *routes*
block routerLink
: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!
Notice the `[routerLink]` binding in the anchor tag.
We bind the `RouterLink` directive (another of the `ROUTER_DIRECTIVES`) to a list
that tells the router where to navigate when the user clicks the link.
At this stage, our `AppComponent` looks like this.
+makeExample('toh-5/dart/lib/app_component_2.dart',null, 'lib/app_component.dart (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*.
We define a *routing instruction* with a *link parameters list*.
The list only has one element in our little sample, the quoted ***name* of the route** to follow.
Looking back at the route configuration, we confirm that `'Heroes'` is the name of the route to the `HeroesComponent`.
.l-sub-section
:marked
Learn about the *link parameters list*
in the [Routing](../guide/router.html#link-parameters-array) chapter.
: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.
+makeExample('toh-5/dart/lib/dashboard_component_1.dart',null, 'lib/dashboard_component.dart (v1)')(format=".")
:marked
Well come back and make it more useful later.
### Configure the dashboard route
Go back to `app_component.dart` and teach it to navigate to the dashboard.
Import the `DashboardComponent` so we can reference it in the dashboard route definition.
Add the following `'Dashboard'` route definition to the `@RouteConfig` list of definitions.
+makeExample('toh-5/dart/lib/app_component.dart','dashboard-route', 'lib/app_component.dart (Dashboard route)')(format=".")
.l-sub-section
block redirect-vs-use-as-default
:marked
**useAsDefault**
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.
We don't have a route for that path and we'd rather not create one.
Fortunately we can add the `useAsDefault: true` property to the *route definition* and the
We don't need a route definition for that. Instead,
we add `useAsDefault: true` to the dashboard *route definition* and the
router will display the dashboard when the browser URL doesn't match an existing route.
:marked
Finally, add a dashboard navigation link to the template, just above the *Heroes* link.
+makeExample('toh-5/dart/lib/app_component.dart','template', 'lib/app_component.dart (template)')(format=".")
.l-sub-section
block templateUrl-path-resolution
:marked
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.
:marked
Refresh the browser. The app displays the dashboard and
we can navigate between the dashboard and the heroes.
The value of `templateUrl` can be an [asset][] in this package or another
package. To use an asset in another package, use a full package reference,
such as `'package:some_other_package/dashboard_component.html'`.
## Dashboard Top Heroes
Lets spice up the dashboard by displaying the top four heroes at a glance.
[asset]: https://www.dartlang.org/tools/pub/glossary#asset
Replace the `template` metadata with a `templateUrl` property that points to a new
template file.
+makeExample('toh-5/dart/lib/dashboard_component.dart', 'template-url', 'lib/dashboard_component.dart (templateUrl)')(format=".")
.l-sub-section
block route-params
:marked
We specify the path _all the way back to the application root_ &mdash;
because Angular doesn't support relative paths _by default_.
We _can_ switch to [component-relative paths](../cookbook/component-relative-paths.html) if we prefer.
:marked
Create that file with these contents:
+makeExample('toh-5/dart/lib/dashboard_component.html', null, 'lib/dashboard_component.html')(format=".")
:marked
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 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`.
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 have work to do, starting with those heroes.
### Share the *HeroService*
We'd like to re-use the `HeroService` to populate the component's `heroes` list.
Recall earlier in the chapter that we removed the `HeroService` from the `providers` list of the `HeroesComponent`
and added it to the `providers` list of the top level `AppComponent`.
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`.
### Get heroes
Open the `dashboard_component.dart` and add the requisite `import` statements.
+makeExample('toh-5/dart/lib/dashboard_component_2.dart','imports', 'lib/dashboard_component.dart (imports)')(format=".")
:marked
We need `OnInit` interface because we'll initialize the heroes in the `ngOnInit` method as we've done before.
Now implement the `DashboardComponent` class like this:
+makeExample('toh-5/dart/lib/dashboard_component_2.dart','component', 'lib/dashboard_component.dart (class)')
:marked
We saw this kind of logic before in the `HeroesComponent`.
* create a `heroes` list property
* 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.
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.
Refresh the browser and see four heroes in the new dashboard.
.l-main-section
:marked
## Navigate to Hero Details
Although we display the details of a selected hero at the bottom of the `HeroesComponent`,
we don't yet *navigate* to the `HeroDetailComponent` in the three ways specified in our requirements:
1. from the *Dashboard* 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.
Adding a `'HeroDetail'` route seem an obvious place to start.
### Routing to a hero detail
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*.
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.
code-example(format='').
&lt;my-hero-detail [hero]="selectedHero">&lt;/my-hero-detail>
:marked
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.
### 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:
code-example(format='').
/detail/11
:marked
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`.
### Configure a Route with a Parameter
Here's the *route definition* we'll use.
+makeExample('toh-5/dart/lib/app_component.dart','hero-detail-route', 'lib/app_component.dart (route to HeroDetailComponent)')(format=".")
:marked
The colon (:) in the path indicates that `:id` is a placeholder to be filled with a specific hero `id`
when navigating to the `HeroDetailComponent`.
.l-sub-section
block ngOnInit
:marked
Of course we have to import the `HeroDetailComponent` before we create this route:
+makeExample('toh-5/dart/lib/app_component.dart','hero-detail-import')(format=".")
:marked
We're finished with the `AppComponent`.
Inside the `ngOnInit` lifecycle hook, extract the `id` parameter value from the `RouteParams` service
and use the `HeroService` to fetch the hero with that `id`.
We won't add a `'Hero Detail'` link to the template because users
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.
We'll get to those *hero* clicks later in the chapter.
There's no point in working on them until the `HeroDetailComponent`
is ready to be navigated *to*.
That will require an `HeroDetailComponent` overhaul.
.l-main-section
:marked
## Revise the *HeroDetailComponent*
Before we rewrite the `HeroDetailComponent`, let's review what it looks like now:
+makeExample('toh-4/dart/lib/hero_detail_component.dart', null, 'lib/hero_detail_component.dart (current)')
: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.
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`.
+makeExample('toh-5/dart/lib/hero_detail_component.dart', 'import-route-params')(format=".")
:marked
We import the `HeroService`so we can fetch a hero.
+makeExample('toh-5/dart/lib/hero_detail_component.dart', 'import-hero-service')(format=".")
:marked
We use the `OnInit` interface from the already imported `angular2/core.dart` package because we'll
call the `HeroService` inside the `ngOnInit` component lifecycle hook.
We inject both the `RouteParams` service and the `HeroService` into the constructor as we've done before,
making private variables for both:
+makeExample('toh-5/dart/lib/hero_detail_component.dart', 'ctor', 'lib/hero_detail_component.dart (constructor)')(format=".")
:marked
Inside the `ngOnInit` lifecycle hook, extract the `id` parameter value from the `RouteParams` service
and use the `HeroService` to fetch the hero with that `id`.
+makeExample('toh-5/dart/lib/hero_detail_component.dart', 'ng-oninit', 'lib/hero_detail_component.dart (ngOnInit)')(format=".")
:marked
Notice how we extract the `id` by calling the `RouteParams.get` method.
+makeExample('toh-5/dart/lib/hero_detail_component.dart', 'get-id')(format=".")
:marked
The hero `id` is a number. Route parameters are *always strings*.
So we convert the route parameter value to a number with the `int.parse` static method.
### Add *HeroService.getHero*
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.
Open `HeroService` and add the `getHero` method. It's trivial given that we're still faking data access:
+makeExample('toh-5/dart/lib/hero_service.dart', 'get-hero', 'lib/hero_service.dart (getHero)')(format=".")
:marked
Return to the `HeroDetailComponent` to clean up loose ends.
### Find our way back
We can navigate *to* the `HeroDetailComponent` in several ways.
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.
We'll add a third option, a `goBack` method that navigates backward one step in the browser's history stack
+makeExample('toh-5/dart/lib/hero_detail_component.dart', 'go-back', 'lib/hero_detail_component.dart (goBack)')(format=".")
.l-sub-section
block extract-id
:marked
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,
perhaps with the [*routerCanDeactivate* hook](../api/router/index/CanDeactivate-interface.html).
:marked
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/dart/lib/hero_detail_component.html', 'back-button')(format=".")
:marked
Modifing the template to add this button spurs us to take one more incremental improvement and migrate the template to its own file
called `hero_detail_component.html`
+makeExample('toh-5/dart/lib/hero_detail_component.html', '', 'lib/hero_detail_component.html')(format=".")
:marked
We update the component metadata with a `templateUrl` pointing to the template file that we just created.
+makeExample('toh-5/dart/lib/hero_detail_component.dart', 'template-url', 'lib/hero_detail_component.dart (templateUrl)')(format=".")
:marked
Here's the (nearly) finished `HeroDetailComponent`:
+makeExample('toh-5/dart/lib/hero_detail_component.dart', 'v2', 'lib/hero_detail_component.dart (latest)')(format=".")
Notice how we extract the `id` by calling the `RouteParams.get` method.
.l-main-section
:marked
## 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.
In the dashboard template we bound each hero's click event to the `gotoDetail` method, passing along the selected `hero` entity.
+makeExample('toh-5/dart/lib/dashboard_component.html','click', 'lib/dashboard_component.html (click binding)')(format=".")
:marked
We stubbed the `gotoDetail` method when we rewrote the `DashboardComponent`.
Now we give it a real implementation.
+makeExample('toh-5/dart/lib/dashboard_component.dart','goto-detail', 'lib/dashboard_component.dart (gotoDetail)')(format=".")
:marked
The `gotoDetail` method navigates in two steps:
1. set a route *link parameters list*
1. pass the list to the router's navigate method.
We wrote *link parameters lists* in the `AppComponent` for the navigation links.
Those lists had only one element, the name of the destination route.
This list has two elements, the ***name*** of the destination route and a ***route parameter object***
with an `id` field set to the value of the selected hero's `id`.
The two list items align with the ***name*** and ***:id*** token in the parameterized `HeroDetail` route configuration we added to `AppComponent` earlier in the chapter.
+makeExample('toh-5/dart/lib/app_component.dart','hero-detail-route', 'lib/app_component.dart (hero detail route)')(format=".")
:marked
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`):
+makeExample('toh-5/dart/lib/dashboard_component.dart','import-router', 'lib/dashboard_component.dart (excerpts)')(format=".")
+makeExample('toh-5/dart/lib/dashboard_component.dart','ctor')(format=".")
:marked
Refresh the browser and select a hero from the dashboard; the app should navigate directly to that heros details.
.l-main-section
:marked
## Select a Hero 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
at the top and details of the selected hero below.
+makeExample('toh-4/dart/lib/app_component.dart','template', 'lib/heroes_component.dart (current template)')(format=".")
:marked
Delete the last line of the template with the `<my-hero-detail>` tags.
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.
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.
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 following HTML fragment at the bottom of the template where the `<my-hero-detail>` used to be:
+makeExample('toh-5/dart/lib/heroes_component.html','mini-detail')(format=".")
:marked
After clicking a hero, the user should see something like this below the hero list:
figure.image-display
img(src='/resources/images/devguide/toh/mini-hero-detail.png' alt="Mini Hero Detail" height="70")
:marked
### Format with 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 ( | ).
+makeExample('toh-5/dart/lib/heroes_component.html','pipe')(format=".")
:marked
Pipes are a good way to format strings, currency amounts, dates and other display data.
Angular ships with several pipes and we can write our own.
.l-sub-section
block heroes-component-cleanup
:marked
Learn about pipes in the [Pipes](../guide/pipes.html) chapter.
:marked
### Move content out of the component file
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.
Because the template for `HeroesComponent` no longer uses `HeroDetailComponent`
directly &mdash; instead using the router to _navigate_ to it &mdash; we can
drop the `directives` argument from `@Component` and remove the unused hero detail
import. The revised `@Component` looks like this:
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.
block css-files
+makeTabs(
`toh-5/dart/lib/hero_detail_component.css,
toh-5/dart/lib/dashboard_component.css`,
null,
`lib/hero_detail_component.css,
lib/dashboard_component.css`)
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 styles contents into a new `heroes_component.css` file.
1. *Set* the component metadata's `templateUrl` and `styleUrls` properties to refer to both files.
Because the template for `HeroesComponent` no longer uses `HeroDetailComponent`
directly &mdash; instead using the router to _navigate_ to it &mdash; we can
remove `HeroDetailComponent` from the directives list. That
list is now empty, so we can remove the `directives` argument. The revised
`@Component` looks like this:
+makeExample('toh-5/dart/lib/heroes_component.dart', 'metadata', 'lib/heroes_component.dart (revised metadata)')(format=".")
:marked
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. Inject the `router` in the constructor (along with the `HeroService`)
1. Implement the `gotoDetail` method by calling the `router.navigate` method
with a two-part `HeroDetail` *link parameters list*.
Here's the revised component class:
+makeExample('toh-5/dart/lib/heroes_component.dart', 'class', 'lib/heroes_component.dart (class)')
:marked
Refresh the browser and start clicking.
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.
We can jump back and forth between the dashboard and the heroes.
We've met all of the navigational requirements that propelled this chapter.
.l-main-section
:marked
## Styling the App
The app is functional but pretty ugly.
Our creative designer team provided some CSS files to make it look better.
### A Dashboard with Style
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.
If we paste these ~60 lines into the component `styles` metadata,
they'll completely obscure the component logic.
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
that file in the component metadata's `styleUrls` list property like this:
+makeExample('toh-5/dart/lib/dashboard_component.dart', 'css', 'lib/dashboard_component.dart (styleUrls)')(format=".")
:marked
.l-sub-section
:marked
The `styleUrls` property is a list of style file names (with paths).
We could list multiple style files from different locations if we needed them.
As with `templateUrl`, we must specify the path _all the way back to the application root_.
:marked
### Stylish Hero Details
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
the `styleUrls` list as we did for `DashboardComponent`.
Here's the content for the aforementioned component CSS files.
+makeTabs(
`toh-5/dart/lib/hero_detail_component.css,
toh-5/dart/lib/dashboard_component.css`,
null,
`lib/hero_detail_component.css,
lib/dashboard_component.css`)
:marked
### Style the Navigation Links
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.
Add a `app_component.css` file to the `app` folder with the following content.
+makeExample('toh-5/dart/lib/app_component.css', '', 'lib/app_component.css (navigation styles)')
.l-sub-section
block router-link-active
:marked
**The *router-link-active* class**
The Angular Router adds the `router-link-active` class to the HTML navigation element
whose route matches the active route. All we have to do is define the style for it. Sweet!
:marked
Set the `AppComponent`s `styleUrls` property to this CSS file.
+makeExample('toh-5/dart/lib/app_component.dart','style-urls', 'lib/app_component.dart (styleUrls)')(format=".")
:marked
### Global application styles
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.
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.
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
introduced earlier (see
[QuickStart, "Add some style"](../quickstart.html#!#add-some-style)).
Here is an excerpt.
+makeExample('toh-5/ts/styles.1.css', 'toh-excerpt', 'styles.css (app styles excerpt)')(format=".")
- var styles_css = 'https://raw.githubusercontent.com/angular/angular.io/master/public/docs/_examples/styles.css'
:marked
Add a new file named `styles.css` in the root folder, if there isn't one already.
Ensure that it contains the [master styles given here](!{styles_css}).
If necessary, also edit `index.html` to refer to this stylesheet.
+makeExample('toh-5/ts/index.html','css', 'index.html (link ref)')(format=".")
:marked
Look at the app now. Our dashboard, heroes, and navigation links are styling!
figure.image-display
img(src='/resources/images/devguide/toh/dashboard-top-heroes.png' alt="View navigations")
.l-main-section
:marked
## Application structure and code
Review the sample source code in the <live-example></live-example> for this chapter.
Verify that we have the following structure:
.filetree
.file angular2_tour_of_heroes
.children
.file lib
block file-tree-end
.filetree
.file angular2_tour_of_heroes
.children
.file app_component.dart
.file app_component.css
.file dashboard_component.css
.file dashboard_component.html
.file dashboard_component.dart
.file hero.dart
.file hero_detail_component.css
.file hero_detail_component.html
.file hero_detail_component.dart
.file hero_service.dart
.file heroes_component.css
.file heroes_component.html
.file heroes_component.dart
.file main.dart
.file mock_heroes.dart
.file web
.children
.file main.dart
.file index.html
.file styles.css
.file pubspec.yaml
.l-main-section
:marked
## Recap
### The Road Behind
We travelled a great distance in this chapter
- We added the Angular *Component Router* to navigate among different components.
- We learned how to create router links to represent navigation menu items.
- We used router parameters to navigate to the details of user selected hero.
- We shared the `HeroService` among multiple components.
- We moved HTML and CSS out of the component file and into their own files.
- We added the `uppercase` pipe to format data.
### The Road Ahead
We have much of the foundation we need to build an application.
We're still missing a key piece: remote data access.
In the next chapter,
well replace our mock data with data retrieved from a server using http.
.file lib
.children
.file app_component.css
.file app_component.dart
.file dashboard_component.css
.file dashboard_component.dart
.file dashboard_component.html
.file hero.dart
.file hero_detail_component.css
.file hero_detail_component.dart
.file hero_detail_component.html
.file hero_service.dart
.file heroes_component.css
.file heroes_component.dart
.file heroes_component.html
.file mock_heroes.dart
.file web
.children
.file index.html
.file main.dart
.file styles.css
.file pubspec.yaml

File diff suppressed because it is too large Load Diff

View File

@ -568,7 +568,7 @@ block filetree
.file index.html
.file package.json
.file styles.css
.file systemjs.config.json
.file systemjs.config.js
.file tsconfig.json
.file typings.json

File diff suppressed because it is too large Load Diff