{ "id": "tutorial/toh-pt5", "title": "Add navigation with routing", "contents": "\n\n\n
There are new requirements for the Tour of Heroes app:
\n For the sample application that this page describes, see the
When you’re done, users will be able to navigate the application like this:
\nAppRoutingModule
linkIn Angular, the best practice is to load and configure the router in a separate, top-level module\nthat is dedicated to routing and imported by the root AppModule
.
By convention, the module class name is AppRoutingModule
and it belongs in the app-routing.module.ts
in the src/app
folder.
Use the CLI to generate it.
\n--flat
puts the file in src/app
instead of its own folder.
\n--module=app
tells the CLI to register it in the imports
array of the AppModule
.
The generated file looks like this:
\nReplace it with the following:
\nFirst, the app-routing.module.ts
file imports RouterModule
and Routes
so the application can have routing functionality. The next import, HeroesComponent
, will give the Router somewhere to go once you configure the routes.
Notice that the CommonModule
references and declarations
array are unnecessary, so are no\nlonger part of AppRoutingModule
. The following sections explain the rest of the AppRoutingModule
in more detail.
The next part of the file is where you configure your routes.\nRoutes tell the Router which view to display when a user clicks a link or\npastes a URL into the browser address bar.
\nSince app-routing.module.ts
already imports HeroesComponent
, you can use it in the routes
array:
A typical Angular Route
has two properties:
path
: a string that matches the URL in the browser address bar.component
: the component that the router should create when navigating to this route.This tells the router to match that URL to path: 'heroes'
\nand display the HeroesComponent
when the URL is something like localhost:4200/heroes
.
RouterModule.forRoot()
linkThe @NgModule
metadata initializes the router and starts it listening for browser location changes.
The following line adds the RouterModule
to the AppRoutingModule
imports
array and\nconfigures it with the routes
in one step by calling\nRouterModule.forRoot()
:
The method is called forRoot()
because you configure the router at the application's root level.\nThe forRoot()
method supplies the service providers and directives needed for routing,\nand performs the initial navigation based on the current browser URL.
Next, AppRoutingModule
exports RouterModule
so it will be available throughout the app.
RouterOutlet
linkOpen the AppComponent
template and replace the <app-heroes>
element with a <router-outlet>
element.
The AppComponent
template no longer needs <app-heroes>
because the application will only display the HeroesComponent
when the user navigates to it.
The <router-outlet>
tells the router where to display routed views.
The RouterOutlet
is one of the router directives that became available to the AppComponent
\nbecause AppModule
imports AppRoutingModule
which exported RouterModule
. The ng generate
command you ran at the start of this tutorial added this import because of the --module=app
flag. If you manually created app-routing.module.ts
or used a tool other than the CLI to do so, you'll need to import AppRoutingModule
into app.module.ts
and add it to the imports
array of the NgModule
.
You should still be running with this CLI command.
\nThe browser should refresh and display the application title but not the list of heroes.
\nLook at the browser's address bar.\nThe URL ends in /
.\nThe route path to HeroesComponent
is /heroes
.
Append /heroes
to the URL in the browser address bar.\nYou should see the familiar heroes master/detail view.
routerLink
)linkIdeally, users should be able to click a link to navigate rather\nthan pasting a route URL into the address bar.
\nAdd a <nav>
element and, within that, an anchor element that, when clicked,\ntriggers navigation to the HeroesComponent
.\nThe revised AppComponent
template looks like this:
A routerLink
attribute is set to \"/heroes\"
,\nthe string that the router matches to the route to HeroesComponent
.\nThe routerLink
is the selector for the RouterLink
directive\nthat turns user clicks into router navigations.\nIt's another of the public directives in the RouterModule
.
The browser refreshes and displays the application title and heroes link,\nbut not the heroes list.
\nClick the link.\nThe address bar updates to /heroes
and the list of heroes appears.
Make this and future navigation links look better by adding private CSS styles to app.component.css
\nas listed in the final code review below.
Routing makes more sense when there are multiple views.\nSo far there's only the heroes view.
\nAdd a DashboardComponent
using the CLI:
The CLI generates the files for the DashboardComponent
and declares it in AppModule
.
Replace the default file content in these three files as follows:
\nThe template presents a grid of hero name links.
\n*ngFor
repeater creates as many links as are in the component's heroes
array.dashboard.component.css
.The class is similar to the HeroesComponent
class.
heroes
array property.HeroService
into a private heroService
property.ngOnInit()
lifecycle hook calls getHeroes()
.This getHeroes()
returns the sliced list of heroes at positions 1 and 5, returning only four of the Top Heroes (2nd, 3rd, 4th, and 5th).
To navigate to the dashboard, the router needs an appropriate route.
\nImport the DashboardComponent
in the app-routing-module.ts
file.
Add a route to the routes
array that matches a path to the DashboardComponent
.
When the application starts, the browser's address bar points to the web site's root.\nThat doesn't match any existing route so the router doesn't navigate anywhere.\nThe space below the <router-outlet>
is blank.
To make the application navigate to the dashboard automatically, add the following\nroute to the routes
array.
This route redirects a URL that fully matches the empty path to the route whose path is '/dashboard'
.
After the browser refreshes, the router loads the DashboardComponent
\nand the browser address bar shows the /dashboard
URL.
The user should be able to navigate back and forth between the\nDashboardComponent
and the HeroesComponent
by clicking links in the\nnavigation area near the top of the page.
Add a dashboard navigation link to the AppComponent
shell template, just above the Heroes link.
After the browser refreshes you can navigate freely between the two views by clicking the links.
\n\nThe HeroDetailsComponent
displays details of a selected hero.\nAt the moment the HeroDetailsComponent
is only visible at the bottom of the HeroesComponent
The user should be able to get to these details in three ways.
\nIn this section, you'll enable navigation to the HeroDetailsComponent
\nand liberate it from the HeroesComponent
.
HeroesComponent
linkWhen the user clicks a hero item in the HeroesComponent
,\nthe application should navigate to the HeroDetailComponent
,\nreplacing the heroes list view with the hero detail view.\nThe heroes list view should no longer show hero details as it does now.
Open the HeroesComponent
template (heroes/heroes.component.html
) and\ndelete the <app-hero-detail>
element from the bottom.
Clicking a hero item now does nothing.\nYou'll fix that shortly after you enable routing to the HeroDetailComponent
.
A URL like ~/detail/11
would be a good URL for navigating to the Hero Detail view of the hero whose id
is 11
.
Open app-routing.module.ts
and import HeroDetailComponent
.
Then add a parameterized route to the routes
array that matches the path pattern to the hero detail view.
The colon (:) in the path
indicates that :id
is a placeholder for a specific hero id
.
At this point, all application routes are in place.
\nDashboardComponent
hero linkslinkThe DashboardComponent
hero links do nothing at the moment.
Now that the router has a route to HeroDetailComponent
,\nfix the dashboard hero links to navigate via the parameterized dashboard route.
You're using Angular interpolation binding within the *ngFor
repeater\nto insert the current iteration's hero.id
into each\nrouterLink
.
HeroesComponent
hero linkslinkThe hero items in the HeroesComponent
are <li>
elements whose click events\nare bound to the component's onSelect()
method.
Strip the <li>
back to just its *ngFor
,\nwrap the badge and name in an anchor element (<a>
),\nand add a routerLink
attribute to the anchor that\nis the same as in the dashboard template
You'll have to fix the private stylesheet (heroes.component.css
) to make\nthe list look as it did before.\nRevised styles are in the final code review at the bottom of this guide.
While the HeroesComponent
class still works,\nthe onSelect()
method and selectedHero
property are no longer used.
It's nice to tidy up and you'll be grateful to yourself later.\nHere's the class after pruning away the dead code.
\nHeroDetailComponent
linkPreviously, the parent HeroesComponent
set the HeroDetailComponent.hero
\nproperty and the HeroDetailComponent
displayed the hero.
HeroesComponent
doesn't do that anymore.\nNow the router creates the HeroDetailComponent
in response to a URL such as ~/detail/11
.
The HeroDetailComponent
needs a new way to obtain the hero-to-display.\nThis section explains the following:
id
from the routeid
from the server via the HeroService
Add the following imports:
\nInject the ActivatedRoute
, HeroService
, and Location
services\ninto the constructor, saving their values in private fields:
The ActivatedRoute
holds information about the route to this instance of the HeroDetailComponent
.\nThis component is interested in the route's parameters extracted from the URL.\nThe \"id\" parameter is the id
of the hero to display.
The HeroService
gets hero data from the remote server\nand this component will use it to get the hero-to-display.
The location
is an Angular service for interacting with the browser.\nYou'll use it later to navigate back to the view that navigated here.
id
route parameterlinkIn the ngOnInit()
lifecycle hook\ncall getHero()
and define it as follows.
The route.snapshot
is a static image of the route information shortly after the component was created.
The paramMap
is a dictionary of route parameter values extracted from the URL.\nThe \"id\"
key returns the id
of the hero to fetch.
Route parameters are always strings.\nThe JavaScript (+) operator converts the string to a number,\nwhich is what a hero id
should be.
The browser refreshes and the application crashes with a compiler error.\nHeroService
doesn't have a getHero()
method.\nAdd it now.
HeroService.getHero()
linkOpen HeroService
and add the following getHero()
method with the id
after the getHeroes()
method:
Note the backticks ( ` ) that define a JavaScript\ntemplate literal for embedding the id
.
Like getHeroes()
,\ngetHero()
has an asynchronous signature.\nIt returns a mock hero as an Observable
, using the RxJS of()
function.
You'll be able to re-implement getHero()
as a real Http
request\nwithout having to change the HeroDetailComponent
that calls it.
The browser refreshes and the application is working again.\nYou can click a hero in the dashboard or in the heroes list and navigate to that hero's detail view.
\nIf you paste localhost:4200/detail/11
in the browser address bar,\nthe router navigates to the detail view for the hero with id: 11
, \"Dr Nice\".
By clicking the browser's back button,\nyou can go back to the hero list or dashboard view,\ndepending upon which sent you to the detail view.
\nIt would be nice to have a button on the HeroDetail
view that can do that.
Add a go back button to the bottom of the component template and bind it\nto the component's goBack()
method.
Add a goBack()
method to the component class that navigates backward one step\nin the browser's history stack\nusing the Location
service that you injected previously.
Refresh the browser and start clicking.\nUsers can navigate around the app, from the dashboard to hero details and back,\nfrom heroes list to the mini detail to the hero details and back to the heroes again.
\nHere are the code files discussed on this page.
\n\n\nAppRoutingModule
, AppModule
, and HeroService
linkAppComponent
linkDashboardComponent
linkHeroesComponent
linkHeroDetailComponent
linkAppComponent
into a navigation shell with <a>
links and a <router-outlet>
.AppRoutingModule
routerLink
directive in anchor elements.HeroService
among multiple components.