Sometimes it makes sense to nest view's or routes within one another. For example on the dashboard you want several sub views, similar to tabs but implemented via the routing system, to show the users' projects, contacts, messages ets. In order to support such scenarios the router allows us to define child routes.
First we adjust our RouterConfig
from above and add the child routes:
import { ProjectsComponent } from '../components/projects.component';
import { MessagesComponent} from '../components/messages.component';
export const appRoutes: RouterConfig = [
{ path: '', pathMatch: 'full', redirectTo: 'login' },
{ path: 'dashboard', component: DashboardComponent,
children: [
{ path: '', redirectTo: 'projects', pathMatch: 'full' },
{ path: 'projects', component: 'ProjectsComponent' },
{ path: 'messages', component: 'MessagesComponent' }
] },
{ path: 'bars/:id', component: BarDetailComponent },
{ path: 'login', component: LoginComponent },
{ path: 'signup', component: SignupComponent }
];
Now that we have our child routes defined we have to make sure those child routes can be displayed within our DashboardComponent
, since that's where we have added the childs to. Previously we have learned that the components are displayed in a <router-outlet></router-outlet>
tag. Similar we declare another RouterOutlet
in the DashboardComponent
:
import { Component } from '@angular/core';
@Component({
selector: 'dashboard',
template: `
<a [routerLink]="['projects']">Projects</a>
<a [routerLink]="['messages']">Messages</a>
<div>
<router-outlet></router-outlet>
</div>
`
})
export class DashboardComponent { }
As you can see, we have added another RouterOutlet
in which the child routes will be displayed. Usually the route with an empty path will be shown, however, we set up a redirect to the projects
route, because we want that to be shown immediately when the dashboard
route is loaded. That being said, we need an empty route, otherwise you'll get an error like this:
Cannot match any routes: 'dashboard'
So by adding the empty route, meaning a route with an empty path, we have defined an entry point for the router.