The AppComponent template no longer needs <app-heroes> because the application only displays 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 because the Angular router is imported with provideRouter in the app.config.ts file.
Try it
If you're not still serving your application, run ng serve to see your application in the browser.
The browser should refresh and display the application title but not the list of heroes.
Look at the browser's address bar. The URL ends in /. The route path to HeroesComponent is /heroes.
Append /heroes to the URL in the browser address bar. You should see the familiar heroes overview/detail view.
Remove /heroes from the URL in the browser address bar. The browser should refresh and display the application title but not the list of heroes.
Add a navigation link using routerLink
Ideally, users should be able to click a link to navigate rather than pasting a route URL into the address bar.
Add a <nav> element and, within that, an anchor element that, when clicked, triggers navigation to the HeroesComponent. The revised AppComponent template looks like this:
A routerLink attribute is set to "/heroes", the string that the router matches to the route to HeroesComponent. The routerLink is the selector for the RouterLink directive that turns user clicks into router navigations. It's another of the public directives in the RouterModule.
The browser refreshes and displays the application title and heroes link, but not the heroes list.
Click the link. The 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 as listed in the final code review below.
Add a dashboard view
Routing makes more sense when your application has more than one view, yet the Tour of Heroes application has only the heroes view.
To add a DashboardComponent, run ng generate as shown here:
ng generate component dashboard
ng generate creates the files for the DashboardComponent.
Replace the default content in these files as shown here:
When the application starts, the browser's address bar points to the web site's root. That doesn't match any existing route so the router doesn't navigate anywhere. The space below the <router-outlet> is blank.
To make the application navigate to the dashboard automatically, add the following route 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 and the browser address bar shows the /dashboard URL.
Add dashboard link to the shell
The user should be able to navigate between the DashboardComponent and the HeroesComponent by clicking links in the navigation 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.
Navigating to hero details
The HeroDetailComponent displays details of a selected hero. At the moment the HeroDetailComponent is only visible at the bottom of the HeroesComponent
The user should be able to get to these details in three ways.
By clicking a hero in the dashboard.
By clicking a hero in the heroes list.
By pasting a "deep link" URL into the browser address bar that identifies the hero to display.
This section enables navigation to the HeroDetailComponent and liberates it from the HeroesComponent.
Delete hero details from HeroesComponent
When the user clicks a hero in HeroesComponent, the application should navigate to the HeroDetailComponent, replacing the heroes list view with the hero detail view. The heroes list view should no longer show hero details as it does now.
Open the heroes/heroes.component.html and delete the <app-hero-detail> element from the bottom.
Clicking a hero item now does nothing. You can fix that after you enable routing to the HeroDetailComponent.
Add a hero detail route
A URL like ~/detail/11 would be a good URL for navigating to the Hero Detail view of the hero whose id is 11.
Add a parameterized route to the routes array that matches the path pattern to the hero detail view.
Remove the inner HTML of <li>. Wrap the badge and name in an anchor <a> element. Add a routerLink attribute to the anchor that's the same as in the dashboard template.
Be sure to fix the private style sheet in heroes.component.css to make the list look as it did before. Revised styles are in the final code review at the bottom of this guide.
Remove dead code - optional
While the HeroesComponent class still works, the onSelect() method and selectedHero property are no longer used.
It's nice to tidy things up for your future self. Here's the class after pruning away the dead code.
Routable HeroDetailComponent
The parent HeroesComponent used to set the HeroDetailComponent.hero property and the HeroDetailComponent displayed the hero.
HeroesComponent doesn't do that anymore. Now the router creates the HeroDetailComponent in response to a URL such as ~/detail/12.
The HeroDetailComponent needs a new way to get the hero to display. This section explains the following:
Get the route that created it
Extract the id from the route
Get the hero with that id from the server using the HeroService
If you are using WebStorm as your IDE, it will usually help you and automatically create the imports, as soon as you use those elements. Ask your instructor for a demo.
Inject the ActivatedRoute, HeroService, and Location services, saving their values in private fields:
The ActivatedRoute holds information about the route to this instance of the HeroDetailComponent. This component is interested in the route's parameters extracted from the URL. The "id" parameter is the id of the hero to display.
The HeroService gets hero data from the remote server and this component uses it to get the hero-to-display.
The location is an Angular service for interacting with the browser. This service lets you navigate back to the previous view.
Extract the id route parameter
In the ngOnInit() lifecycle hook call 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. The "id" key returns the id of the hero to fetch.
Route parameters are always strings. The JavaScript Number function converts the string to a number, which is what a hero id should be.
The browser refreshes and the application crashes with a compiler error. HeroService doesn't have a getHero() method. Add it now.
Add HeroService.getHero()
Open HeroService and add the following getHero() method with the id after the getHeroes() method:
getHero(id: number): Observable<Hero> {// For now, assume that a hero with the specified `id` always exists.// Error handling will be added in the next step of the tutorial. const hero =HEROES.find(h =>h.id === id)!; this.messageService.add(`HeroService: fetched hero id=${id}`); return of(hero);}
IMPORTANT:
The backtick ( ` ) characters define a JavaScript template literal for embedding the id.
Like getHeroes(), getHero() has an asynchronous signature. It returns a mock hero as an Observable, using the RxJS of() function.
You can rewrite getHero() as a real Http request without having to change the HeroDetailComponent that calls it.
Try it
The browser refreshes and the application is working again. You can click a hero in the dashboard or in the heroes list and navigate to that hero's detail view.
If you paste localhost:4200/detail/12 in the browser address bar, the router navigates to the detail view for the hero with id: 12, Dr Nice.
Find the way back
By clicking the browser's back button, you can go back to the previous page. This could be the hero list or dashboard view, depending upon which sent you to the detail view.
It 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 to the component's goBack() method.
Add a goBack()method to the component class that navigates backward one step in the browser's history stack using the Location service that you used to inject.
goBack(): void {this.location.back();}
Refresh the browser and start clicking. Users can now navigate around the application using the new buttons.
The details look better when you add the private CSS styles to hero-detail.component.css as listed in one of the "final code review" tabs below.