We received new requirements for our Tour of Heroes application:
- Add a Dashboard view.
- Navigate between the Heroes and Dashboard views.
- Clicking on a hero in either view navigates to a detail view of the selected hero.
- Clicking a deep link in an email opens the detail view for a particular hero.
When we’re done, users will be able to navigate the app like this:
We'll add Angular’s Router to our app to satisfy these requirements.
The Routing and Navigation chapter covers the router in more detail than we will in this tutorial.
To see the URL changes in the browser address bar of the live example, open it again in the Plunker editor by clicking the icon in the upper right, then pop out the preview window by clicking the blue 'X' button in the upper right corner.
Where We Left Off
Before we continue with our Tour of Heroes, let’s verify that we have the following structure after adding our hero service and hero detail component. If not, we’ll need to go back and follow the previous chapters.
Keep the app transpiling and running
Open a terminal/console window and enter the following command to start the TypeScript compiler, start the server, and watch for changes:
The application runs and updates automatically as we continue to build the Tour of Heroes.
Here's our plan:
AppComponentinto an application 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
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.
AppComponent should only handle navigation.
Let's move the display of Heroes out of
AppComponent and into its own
AppComponent is already dedicated to Heroes.
Instead of moving anything out of
AppComponent, we'll just rename it
and create a new
AppComponent shell separately.
The steps are to rename:
- app.component.ts file to heroes.component.ts
HeroesComponent(rename locally, only in this file)
AppComponent will be the application shell.
It will have some navigation links at the top and a display area below for the pages we navigate to.
The initial steps are:
- Create the file src/app/app.component.ts.
- Define an exported
- Add an
@Componentdecorator above the class with a
- Move the following from
<h1>element, which contains a binding to
- Add a
<my-heroes>element to the app template just below the heading so we still see the heroes.
AppModuleso Angular recognizes the
AppModulebecause we'll need it in every other view.
providersarray since it has been promoted.
- Add the supporting
Our first draft looks like this:
The app still runs and still displays heroes.
Our refactoring of
AppComponent into a new
AppComponent and a
We have done no harm.
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 Router.
The Angular router is an external, optional Angular NgModule called
The router is a combination of multiple provided services (
multiple directives (
RouterOutlet, RouterLink, RouterLinkActive),
and a configuration (
Routes). We'll configure our routes first.
index.html and ensure there is a
<base href="..."> element
(or a script that dynamically sets this element)
at the top of the
See the base href section of the router
guide to learn why this matters, and what to add if the
element is missing.
Our application doesn't have any routes yet. We'll start by creating a configuration for the application 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 as a route to the heroes component:
Routes are an array of route definitions.
We have only one route definition at the moment but rest assured, we'll add more.
This route definition has the following parts:
- path: the router matches this route's path to the URL in the browser address bar (
- name: the official name of the route;
it must begin with a capital letter to avoid confusion with the path (
- component: the component that the router should create when navigating to this route (
Learn more about defining routes with
Routes in the Routing chapter.
Make the router available
We've setup the initial route configuration. Now we'll add it to our
We'll add our configured
RouterModule to the
AppModule imports array.
We use the
forRoot method because we're providing a configured router at the root of the application.
forRoot method gives us the Router service providers and directives needed for routing, and
performs the initial navigation based on the current browser URL.
If we paste the path,
/heroes, into the browser address bar,
the router should match it to the
heroes route and display the
We have to tell it where by adding a
<router-outlet> element to the bottom of the template.
RouterOutlet is one of the directives provided by the
The router displays each component immediately below the
<router-outlet> as we navigate through the application.
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
The revised template looks like this:
routerLink binding in the anchor tag.
We bind the
RouterLink directive (another of the
RouterModule directives) to a string
that tells the router where to navigate when the user clicks the link.
Since our link is not dynamic, we define a routing instruction with a one-time binding to our route path.
Looking back at the route configuration, we confirm that
'/heroes' is the path of the route to the
Learn more about dynamic router links and the link parameters array in the Routing chapter.
Refresh the browser. We see only the app title and heroes link. We don't see the heroes list.
The browser's address bar shows
The route path to
We don't have a route that matches the path
/, so there is nothing to show.
That's something we'll want to fix.
We click the Heroes navigation link, the browser bar updates to
and now we see the list of heroes. We are navigating at last!
At this stage, our
AppComponent looks like this.
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.
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.
We’ll come back and make it more useful later.
Configure the dashboard route
Go back to
app.module.ts and teach it to navigate to the dashboard.
Import the dashboard component and
add the following route definition to the
Routes array of definitions.
Also import and add
DashboardComponent to our
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
Remember that the browser launches with
/ in the address bar.
We can use a redirect route to make this happen. Add the following to our array of route definitions:
Learn about the redirects in the Routing chapter.
Add navigation to the template
Finally, add a dashboard navigation link to the template, just above the Heroes link.
We nested the two links within
They don't do anything yet but they'll be convenient when we style the links a little later in the chapter.
To see these changes in your browser, go to the application root (
/) and reload.
The app displays the dashboard and we can navigate between the dashboard and the heroes.
Dashboard Top Heroes
Let’s spice up the dashboard by displaying the top four heroes at a glance.
template metadata with a
templateUrl property that points to a new
moduleId property to
module.id for module-relative loading of the
Create that file with this content:
*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.
Share the HeroService
We'd like to re-use the
HeroService to populate the component's
Recall earlier in the chapter that we removed the
HeroService from the
providers array of
and added it to the
providers array of
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
Open dashboard.component.ts and add the requisite
Now implement the
DashboardComponent class like this:
We've seen this kind of logic before 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 we cherry-pick four heroes (2nd, 3rd, 4th, and 5th) with the
Refresh the browser and see four heroes in the new dashboard.
Navigate to Hero Details
Although we display the details of a selected hero at the bottom of the
we don't yet navigate to the
HeroDetailComponent in the three ways specified in our requirements:
- 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.
Adding a hero-detail route seems like an obvious place to start.
Routing to a hero detail
We'll add a route to the
app.module.ts 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
At the moment the parent
HeroesComponent sets the component's
hero property to a
hero object with a binding like this.
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.
We can add the hero's
id to the URL. When routing to the hero whose
id is 11,
we could expect to see a URL such as this:
/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
Configure a Route with a Parameter
Here's the route definition we'll use.
The colon (:) in the path indicates that
:id is a placeholder to be filled with a specific hero
when navigating to the
We're finished with the application routes.
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
is ready to be navigated to.
That will require an
Revise the HeroDetailComponent
Before we rewrite the
HeroDetailComponent, let's review what it looks like now:
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.
HeroDetailComponent should take the
id parameter from the
ActivatedRoute service and use the
HeroService to fetch the hero with that
First, add the requisite imports:
Let's have the
ActivatedRoute service, the
HeroService and the
Location service injected
into the constructor, saving their values in private fields:
Also import the
switchMap operator to use later with the route parameters
We tell the class that we want to implement the
ngOnInit lifecycle hook, we use the
params observable to
id parameter value from the
and use the
HeroService to fetch the hero with that
Note how the
switchMap operator maps the id in the observable route parameters
to a new
Observable, the result of the
If the user re-navigates to this component while a getHero request is still inflight,
switchMap cancels that old request before calling
id is a number. Route parameters are always strings.
Do I need to unsubscribe?
Router manages the observables it provides and localizes
the subscriptions. The subscriptions are cleaned up when the component is destroyed, protecting against
memory leaks, so we don't need to unsubscribe from the route params
The problem with this bit of code is that
HeroService doesn't have a
We better fix that quickly before someone notices that we broke the app.
HeroService and add a
getHero method that filters the heroes list from
Let's 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
Location service we injected previously.
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 CanDeactivate guard.
Then we wire this method with an event binding to a Back button that we add to the bottom of the component template.
Modifying 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:
We update the component metadata with a
moduleId and a
templateUrl pointing to the template file that we just created.
Refresh the browser and see the results.
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.
Although the dashboard heroes are presented as button-like blocks, they should behave like anchor tags. When hovering over a hero block, 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, reopen the dashboard.component.html and replace the repeated
<div *ngFor...> tags
<a> tags. The opening
<a> tag looks like this:
Top level navigation in the
template has router links set to fixed paths of the
destination routes, "/dashboard" and "/heroes".
This time, we're binding to an expression containing a link parameters array.
The array has two elements, the path of
the destination route and a route parameter set to the value of the current hero's
The two array items align with the path and :id
token in the parameterized hero detail route definition we added to
app.module.ts earlier in the chapter:
Refresh the browser and select a hero from the dashboard; the app should navigate directly to that hero’s details.
Refactor routes to a Routing Module
Almost 20 lines of
AppModule are devoted to configuring four routes.
Most applications have many more routes and they add guard services
to protect against unwanted or unauthorized navigations.
Routing considerations could quickly dominate this module and obscure its primary purpose which is to
establish key facts about the entire app for the Angular compiler.
We should refactor the routing configuration into its own class.
What kind of class?
RouterModule.forRoot() produces an Angular
ModuleWithProviders which suggests that a
class dedicated to routing should be some kind of module.
It should be a Routing Module.
By convention the name of a Routing Module contains the word "Routing" and aligns with the name of the module that declares the components navigated to.
app-routing.module.ts file as a sibling to
app.module.ts. Give it the following contents extracted from the
Noteworthy points, typical of Routing Modules:
Pulls the routes into a variable. You might export it in future and it clarifies the Routing Module pattern.
exportsso that the components in the companion module have access to Router declarables such as
declarations! Declarations are the responsibility of the companion module.
providersfor guard services if you have them; there are none in this example.
Now delete the routing configuration from
AppModule and import the
(both with an ES
import statement and by adding it to the
Here is the revised
AppModule, compared to its pre-refactor state:
It's simpler and focused on identifying the key pieces of the application.
Select a Hero in the HeroesComponent
Earlier we added the ability to select a hero from the dashboard.
We'll do something similar in the
HeroesComponent template exhibits a "master/detail" style with the list of heroes
at the top and details of the selected hero below.
Our goal is to move the detail to its own view and navigate to it when the user decides to edit a selected hero.
<h1> at the top (we forgot about it during the
Delete the last line of the template with the
We'll no longer show the full
We're going to display the hero detail on its own page and route to it as we did in the dashboard.
We'll throw in a small twist for variety. We are keeping the "master/detail" style but shrinking the detail to a "mini", read-only version. When the user selects a hero from the list, we don't go to the detail page. We 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:
After clicking a hero, the user should see something like this below the hero list:
Format with the uppercase pipe
Notice that the hero's name is displayed in CAPITAL LETTERS. That's the effect of the
that we slipped into the interpolation binding. Look for it 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 we can write our own.
Learn about pipes in the Pipes chapter.
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.
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.
Let's migrate the template and the styles to their own files before we make any more changes:
- Cut-and-paste the template contents into a new heroes.component.html file.
- Cut-and-paste the styles contents into a new heroes.component.css file.
- Set the component metadata's
styleUrlsproperties to refer to both files.
- . Set the
styleUrlsare relative to the component.
styleUrls property is an array of style file names (with paths).
We could list multiple style files from different locations if we needed them.
Update the HeroesComponent class.
HeroesComponent navigates to the
HeroDetailComponent in response to a button click.
The button's click event is bound to a
gotoDetail method that navigates imperatively
by telling the router where to go.
This approach requires some changes to the component class:
- Import the
routerfrom the Angular router library
- Inject the
routerin the constructor (along with the
gotoDetailby calling the
Note that we're passing a two-element link parameters array
— a path and the route parameter — to
router.navigate method just as we did in the
back in the
Here's the fully revised
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.
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
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 array property like this:
Stylish Hero Details
The designers also gave us CSS styles specifically for the
Add a hero-detail.component.css to the
folder and refer to that file inside
styleUrls array as we did for
Let's also remove the
and its import
while we are at it.
Here's the content for the aforementioned component CSS files.
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
Add a app.component.css file to the
app folder with the following content.
The routerLinkActive directive
The Angular Router provides a
routerLinkActive directive we can use 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!
moduleId: module.id to the
@Component metadata of the
to enable module-relative file URLs.
Then add a
styleUrls property that points to this CSS file as follows.
Global application styles
When we add styles to a component, we're keeping everything a component needs — HTML, the CSS, the code — 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 installed earlier during setup. Here is an excerpt:
Create the file styles.css, if it doesn't exist already. Ensure that it contains the master styles given here.
If necessary, also edit index.html to refer to this stylesheet.
Look at the app now. Our dashboard, heroes, and navigation links are styling!
Application structure and code
Review the sample source code in the
The Road Behind
We travelled a great distance in this chapter
- We added the Angular Router to navigate among different components.
- We learned how to create router links to represent navigation menu items.
- We used router link parameters to navigate to the details of user selected hero.
- We shared the
HeroServiceamong multiple components.
- We moved HTML and CSS out of the component file and into their own files.
- We added the
uppercasepipe to format data.
- We refactored routes into a
Routing Modulethat we import.
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, we’ll replace our mock data with data retrieved from a server using http.