There are new requirements for the Tour of Heroes app:
- Add a Dashboard view.
- Add the ability to navigate between the Heroes and Dashboard views.
- When users click a hero name in either view, navigate to a detail view of the selected hero.
- When users click a deep link in an email, open the detail view for a particular hero.
When you’re done, users will be able to navigate the app like this:
To satisfy these requirements, you’ll add Angular’s router to the app.
For more information about the router, read the Routing and Navigation page.
When you’re done with this page, the app should look like this
Where you left off
Before continuing with the Tour of Heroes, verify that you have the following structure.
Here’s the plan:
AppComponentinto an app shell that only handles navigation.
- Relocate the Heroes concerns within the current
AppComponentto a separate
- Add routing.
- Create a new
- Tie the Dashboard into the navigation structure.
Routing is another name for navigation. The router is the mechanism for navigating from view to view.
Splitting the AppComponent
The current app loads
AppComponent and immediately displays the list of heroes.
The revised app should present a shell with a choice of views (Dashboard and Heroes)
and then default to one of them.
AppComponent should only handle navigation, so you’ll
move the display of Heroes out of
AppComponent and into its own
AppComponent is already dedicated to Heroes.
Instead of moving the code out of
AppComponent, rename it to
and create a separate
Do the following:
- Rename and move the
- Drop the
src/prefix from import paths.
- Rename the
HeroesComponent(rename locally, only in this file).
- Rename the selector
- Change the template URL to
heroes_component.htmland style file to
AppComponent is the app shell.
It will have some navigation links at the top and a display area below.
Perform these steps:
- Create the file
- Define an
- Add an
@Componentannotation above the class with a
- Move the following from the heroes component to
<h1>element, which contains a binding to
- Add a
<my-heroes>element to the app template just below the heading so you still see the heroes.
AppComponentso Angular recognizes the
AppComponentbecause you’ll need it in every other view.
providerslist since it was promoted.
- Add the supporting
The first draft looks like this:
open_in_browser Refresh the browser. The app still runs and displays heroes.
Instead of displaying automatically, heroes should display after users click a button. In other words, users should be able to navigate to the list of heroes.
Update the pubspec
Use the Angular router (angular_router) to enable navigation. Since the router is in its own package, first add the package to the app’s pubspec:
+ angular_router: ^1.0.2
Not all apps need routing, which is why the Angular router is in a separate, optional package.
Import the library
Make the router available
To tell Angular that your app uses the router, specify ROUTER_PROVIDERS in your app’s bootstrap function:
The default LocationStrategy is PathLocationStrategy so, in
production, you can use ROUTER_PROVIDERS without the LocationStrategy
During development, it is more convenient to use HashLocationStrategy
pub serve does not support deep linking.
See the Router Appendix on LocationStrategy and browser URL styles
Next, add ROUTER_DIRECTIVES to the
@Component annotation, and remove
You can remove
HeroesComponent from the directives list because
AppComponent won’t directly display heroes; that’s the router’s job. Soon you’ll remove
<my-heroes> from the template.
index.html and ensure there is a
<base href="..."> element
(or a script that dynamically sets this element)
at the top of the
Routes tell the router which views to display when a user clicks a link or pastes a URL into the browser address bar.
Create a route configuration (RouteConfig) to hold a list of app route definitions. Define the first route as a route to the heroes component.
The route definition is a Route object that has the following named arguments:
path: The router matches this string against the URL in the browser address bar (
name: The route name (
Heroes). It must begin with a capital letter to avoid confusion with the path.
component: The component that will be activated when this route is navigated to (
Read more about defining routes in the Routing & Navigation page.
If you visit localhost:8080/#/heroes,
the router should match the URL to the heroes route and display a
However, you have to tell the router where to display the component.
To do this, add a
<router-outlet> element at the end of the template.
RouterOutlet is one of the ROUTER_DIRECTIVES. The router displays each
component immediately below the
<router-outlet> as users navigate through
open_in_browser Refresh the browser, then visit localhost:8080/#/heroes. You should see the heroes list.
Users shouldn’t have to paste a route path into the address bar.
Instead, add an anchor to the template that, when clicked,
triggers navigation to
The revised template looks like this:
[routerLink] binding in the anchor tag. The RouterLink directive
tells the router where to navigate when the user
clicks the link.
You 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, confirm that
'Heroes' is the name of the route to the
Learn about the link parameters list in the Routing chapter.
Refresh the browser. The browser displays the app title and heroes link,
but not the heroes list. Click the Heroes navigation link. The address bar
/#/heroes (or the equivalent
and the list of heroes displays.
AppComponent now looks like this:
The AppComponent has a router and displays routed views. For this reason, and to distinguish it from other kinds of components, this component type is called a router component.
Add a dashboard
Routing only makes sense when multiple views exist.
To add another view, create a placeholder
You’ll make this component more useful later.
Configure the dashboard route
Add a dashboard route similar to the heroes route:
Add a redirect route
Currently, the browser launches with
/ in the address bar.
When the app starts, it should show the dashboard and
/#/dashboard path in the address bar.
To make this happen, add a redirect route:
Add navigation to the dashboard
Add a dashboard navigation link to the template, just above the heroes link.
<nav> tags don’t do anything yet, but they’ll be useful later when you style the links.
In your browser, go to the app root (
/) and reload.
The app displays the dashboard and you can navigate between the dashboard and the heroes list.
Add heroes to the dashboard
To make the dashboard more interesting, you’ll display the top four heroes at a glance.
template metadata with a
templateUrl property that points to a new
template file, and add the directives shown below (you’ll add the necessary imports soon):
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,
Create the template file with this content:
*ngFor is used again to iterate over a list of heroes and display their names.
<div> elements will help with styling later.
Sharing the HeroService
To populate the component’s
heroes list, you can reuse the
Earlier, you removed the
HeroService from the
providers list of
and added it to the
providers list of
That move created a singleton
HeroService instance, available to all components of the app.
HeroService and you can use it in the
dashboard_component.dart, add the following
Now create the
DashboardComponent class like this:
This kind of logic is also used in the
- Define a
- Inject the
HeroServicein the constructor and hold it in a private
- Call the service to get heroes inside the Angular
In this dashboard you specify four heroes (2nd, 3rd, 4th, and 5th).
open_in_browser Refresh the browser to see four hero names in the new dashboard.
Navigating to hero details
While the details of a selected hero displays at the bottom of the
users should be able to navigate to a
HeroDetailComponent in the following additional ways:
- From the dashboard to a selected hero.
- From the heroes list to a selected hero.
- From a “deep link” URL pasted into the browser address bar.
Routing to a hero detail
You can add a route to the
AppComponent, where the other routes are defined.
The new route is unusual in that you must tell the
HeroDetailComponent which hero to show.
You didn’t have to tell the
HeroesComponent or the
Currently, the parent
HeroesComponent sets the component’s
hero property to a
hero object with a binding like this:
But this binding won’t work in any of the routing scenarios.
You can add the hero’s
id to the route path. When routing to the hero whose
id is 11,
you could expect to see a path such as this:
/detail/ part is constant. The trailing numeric
id changes from hero to hero.
You need to represent the variable part of the route with a parameter that stands for the hero’s
Add a route with a parameter
First, import the hero detail component:
Next, add the following route:
The colon (:) in the path indicates that
:id is a placeholder for a specific hero
when navigating to the
You’re finished with the app routes.
You didn’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 name, whether the name is displayed on the dashboard or in the heroes list.
But this won’t work until the
is revised and ready to be navigated to.
Here’s what the
HeroDetailComponent looks like now:
The template won’t change. Hero names will display the same way. The major changes are driven by how you get hero names.
You will no longer receive the hero in a parent component property binding, so
you can remove the
@Input() annotation from the
HeroDetailComponent will take the
id parameter from the router’s
RouteParams service and use the
HeroService to fetch the hero with that
Add the following imports:
Tell the class to implement the
ngOnInit() lifecycle hook, extract the
id parameter value from the
RouteParams service and use the
HeroService to fetch the hero with that
Notice how you can extract the
id by calling the
id is a number. Route parameters are always strings.
So the route parameter value is converted to a number.
ngOnInit(), you used the
getHero() method, which
have yet. To fix this issue, open
HeroService and add a
that filters the heroes list from
Find the way back
Users have several ways to navigate to the
To navigate somewhere else, users can click one of the two links in the
AppComponent or click the browser’s back button.
Now add a third option, a
goBack() method that navigates backward one step in the browser’s history stack
Location service you injected previously.
Going back too far could take users out of the app. In a real app, you can prevent this issue with the routerCanDeactivate() hook. Read more on the CanDeactivate page.
You’ll wire this method with an event binding to a Back button that you’ll add to the component template.
Migrate the template to its own file called
Update the component metadata with a
templateUrl pointing to the template file that you just created.
open_in_browser Refresh the browser and visit localhost:8080/#details/11. Details for hero 11 should be displayed. Selecting a hero in either the dashboard or the heroes list doesn’t work yet. You’ll deal with that next.
Select a dashboard hero
When a user selects a hero in the dashboard, the app should navigate to a
HeroDetailComponent to allow the user to view and edit the selected hero.
The dashboard heroes should behave like anchor tags: when hovering over a hero name, the target URL should display in the browser status bar and the user should be able to copy the link or open the hero detail view in a new tab.
To achieve this effect, open
dashboard_component.html and replace the
<div *ngFor...> element with an anchor
(the child elements remain the same):
[routerLink] binding. As described in the
Router links section of this page, top-level navigation in
AppComponent template has router links set to fixed names of the
This time, you’re binding to an expression containing a link parameters list.
The list has two elements: the name of
the destination route and a route parameter set to the value of the current hero’s
The two list items align with the name and :id in the parameterized hero detail route definition that you added earlier:
open_in_browser Refresh the browser and select a hero from the dashboard; the app navigates to that hero’s details.
Select a hero in the HeroesComponent
the current template exhibits a “master/detail” style with the list of heroes
at the top and details of the selected hero below.
You’ll no longer show the full
Instead, you’ll display the hero detail on its own page and route to it as you did in the dashboard.
Make these changes:
- Remove the
<hero-detail>element from the last line of the template.
HeroDetailComponentfrom list of
- Remove the hero detail import.
When users select a hero from the list, they won’t go to the detail page. Instead, they’ll see a mini detail on this page and have to 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
<hero-detail> used to be:
After clicking a hero (but don’t try now since it won’t work yet), users should see something like this below the hero list:
The hero’s name is displayed in capital letters because of the
that’s included in the interpolation binding, right after the pipe operator ( | ).
Pipes are a good way to format strings, currency amounts, dates and other display data. Angular ships with several pipes and you can write your own.
warning Before you can use an Angular pipe in a
template, you need to list it in the
pipes argument of your component’s
@Component annotation. You can add pipes
individually, or for convenience you can use groups like COMMON_PIPES.
Read more about pipes on the Pipes page.
open_in_browser Refresh the browser. Selecting a hero from the heroes list will activate the mini detail view. The view details button doesn’t work yet.
Update the HeroesComponent class
HeroesComponent navigates to the
HeroesDetailComponent in response to a button click.
The button’s click event is bound to a
gotoDetail() method that should navigate imperatively
by telling the router where to go.
This approach requires the following changes to the component class:
- Import the angular_router.
- Inject the
Routerin the constructor, along with the
gotoDetail()by calling the router
Here’s the revised
gotoDetail(), you’re passing a two-element link parameters list — a
name and the route parameter — to
navigate() method, just as you did in the
back in the
open_in_browser Refresh the browser and start clicking. Users can navigate around the app, from the dashboard to hero details and back, from heroes list to the mini detail to the hero details and back to the heroes again.
You’ve met all of the navigational requirements that propelled this page.
Style the app
The app is functional but it needs styling. The dashboard heroes should display in a row of rectangles. You’ve received around 60 lines of CSS for this purpose, including some simple media queries for responsive design.
As you now know, adding the CSS to the component
would obscure the component logic.
Instead, you’ll add the CSS to separate
dashboard_component.css file in the
lib/src folder and reference
that file in the component metadata’s
styleUrls list property like this:
Hero detail styles
hero_detail_component.css file in the
folder and reference that file in the component metadata’s
Style the navigation links
app_component.css file in the
and reference that file in the component metadata’s
The provided CSS makes the navigation links in the
AppComponent look more like selectable buttons.
Earlier, you surrounded those links with a
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 you have to do is define the style for it.
Global app styles
When you add styles to a component, you keep everything a component needs—HTML, the CSS, the code—together in one convenient place. It’s easy to package it all up and reuse the component somewhere else.
You can also create styles at the app level outside of any component.
The designers provided some basic styles to apply to elements across the entire app. These correspond to the full set of master styles that you installed earlier during setup. Here’s an excerpt:
Create the file
web/styles.css, if necessary.
Ensure that the file contains the master styles provided here.
web/index.html to refer to this stylesheet.
Look at the app now. The dashboard, heroes, and navigation links are styled.
App structure and code
Review the sample source code in the
The road you’ve travelled
Here’s what you achieved in this page:
- You added the Angular router to navigate among different components.
- You learned how to create router links to represent navigation menu items.
- You used router link parameters to navigate to the details of the user-selected hero.
- You shared the
HeroServiceamong multiple components.
- You added the
uppercasepipe to format data.
Your app should look like this
The road ahead
You have much of the foundation you need to build an app. You’re still missing a key piece: remote data access.
In the next page, you’ll replace the mock data with data retrieved from a server using http.