How to use child routes in Angular 2

。_饼干妹妹 提交于 2019-11-27 21:23:36
Pardeep Jain

You just need to import the child component in the routerLink then your code is working fine. For example:

<a [routerLink]="['./HelloCmp','ChildCmp']">hello</a>

Here is the working plnkur of your code. Plunker Code

For more info about this routing see this issue on github here

Update to Angular 2 beta

As of Angular 2 beta some changes are here:

  • router-link has been changed to routerLink

  • You can also use useAsDefault : true instead of providing child at the time of routerLink like this -

    {path: '/blabla', components: ABC , name : ABC, useAsDefault: true}

Angular4 child Routing -

Let me first define the route configuration, each route can have a property called children where you can define the child routes of this route.

const routes: Routes = [
  {path: '', redirectTo: 'home', pathMatch: 'full'},
  {path: 'find', redirectTo: 'search'},
  {path: 'home', component: HomeComponent},
  {path: 'search', component: SearchComponent},
  {
  path: 'artist/:artistId',
  component: ArtistComponent,
  children: [
  {path: '', redirectTo: 'tracks'}, ①
  {path: 'tracks', component: ArtistTrackListComponent}, ②
  {path: 'albums', component: ArtistAlbumListComponent}, ③
  ]
  },
  {path: '**', component: HomeComponent}
];
  1. If a user navigates to say /artist/1234 it will redirect to /artist/1234/tracks .
  2. This route matches a URL like /artist/1234/tracks.
  3. This route matches a URL like /artist/1234/albums.
<h1>Artist</h1>
<p>
  <a [routerLink]="['./tracks']">Tracks</a> |
  <a [routerLink]="['./albums']">Albums</a>
</p>
<router-outlet></router-outlet>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!