Skip to main content

Lab 8.0: Routing

Objectives

  • Implement a router in the application

Instructions

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.ts file and import the RouterModule module using the routes array.

PathComponent
''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 AlbumAddComponent will only display a message for now (You don't need to dom anything in it yet).
  • In your app.component.html file, remove both album-list and album-of-the-day tags and replace with the <router-outlet> directive to tell Angular where to display the routed components.
  • In your home.component.html file, add the <album-of-the-day> tag.
    • Normally the component have some related logic in the app-component file regarding the fact that it can hide the album-of-the-day component. For this lab, we will keep it simple and forget about this feature for now
  • Your app.module.ts routes variable 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.html file 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:4200 should redirect to /home and display the HomeComponent.
  • localhost:4200/album/add should display AlbumAddComponent.
  • localhost:4200/album/list should display AlbumListComponent.
  • In the MenuComponent file, modify the two links so we can navigate to the HomeComponent and the AlbumAddComponent.
  • In the HeaderComponent file, we also want to go to the home page when clicking on the title.