Lab 8.0: Routing
Objectives
Section titled “Objectives”- Implement a router in the application
Instructions
Section titled “Instructions”Step 1: Create some new components and map them to routes
Section titled “Step 1: Create some new components and map them to routes”-
Create the following components:
-
HomeComponent -
PageNotFoundComponent -
AlbumAddComponent -
Create a route for each component in the
app.module.tsfile and import the RouterModule module using the routes array.
| Path | Component |
|---|---|
| ‘’ | redirect to /home |
| ‘home’ | HomeComponent |
| ‘album/list’ | AlbumListComponent |
| ‘album/add’ | AlbumAddComponent |
| ‘**’ | PageNotFound |
- Now your routes are defined you want to display the routed components in the place of the
<router-outlet>directive.- The
AlbumAddComponentwill only display a message for now (You don’t need to dom anything in it yet).
- The
- In your
app.component.htmlfile, remove bothalbum-listandalbum-of-the-daytags and replace with the<router-outlet>directive to tell Angular where to display the routed components. - In your
home.component.htmlfile, add the<album-of-the-day>tag.- Normally the component have some related logic in the
app-componentfile regarding the fact that it can hide thealbum-of-the-daycomponent. For this lab, we will keep it simple and forget about this feature for now
- Normally the component have some related logic in the
- Your app.module.ts
routesvariable file should look somthing like:
const routes: Routes = [ {path: '', redirectTo: '/home', pathMatch: 'full'}, {path: 'home', component: HomeComponent}, {path: 'album/add', component: AlbumAddComponent}, {path: 'album/list', component: AlbumsListComponent}, {path: '**', component: PageNotFoundComponent}][HINT] Dont forget to import the RouterModule. the forRoot method of the RouterModule module should be called with the routes array as a parameter.
- Your
app.component.htmlfile should look something like:
<div> <app-header [title]="title"/> <main> <p> Welcome to {{title}}! In this app you can manage your music collection </p> <router-outlet></router-outlet> </main> <app-footer [title]="title"/></div>At this level.
localhost:4200should redirect to/homeand display theHomeComponent.localhost:4200/album/addshould displayAlbumAddComponent.localhost:4200/album/listshould displayAlbumListComponent.
Step 2: Add links to navigate between routes
Section titled “Step 2: Add links to navigate between routes”- In the
MenuComponentfile, modify the two links so we can navigate to theHomeComponentand theAlbumAddComponent. - In the
HeaderComponentfile, we also want to go to the home page when clicking on the title.

