Router navigate to child route - Angular 6

Ante Ereš picture Ante Ereš · Nov 8, 2018 · Viewed 32.2k times · Source

I've defined my routes like this:

const routes: Routes = [
    { path: '', loadChildren: './tabs/tabs.module#TabsPageModule' },
    { path: 'faq', loadChildren: './faq/faq.module#FaqPageModule' },
    { path: 'terms', loadChildren: './terms/terms.module#TermsPageModule' }
];
@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule {}

and like this:

const routes: Routes = [
  {
    path: 'tabs',
    component: TabsPage,
    children: [
      {
        path: '',
        redirectTo: '/tabs/(list:list)',
        pathMatch: 'full',
      },
      {
        path: 'list',
        outlet: 'list',
        component: ListPage
      },
      {
        path: 'profile',
        outlet: 'profile',
        component: ProfilePage,
        canActivate: [AuthGuardService]
      }
    ]
  },
  {
    path: '',
    redirectTo: '/tabs/(list:list)',
    pathMatch: 'full'
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class TabsPageRoutingModule {}

I am interested how I can navigate to ListPage or ProfilePage using router .navigate() method in component or routerLink in some html element.

I tried something like this

this.router.navigate(['tabs/profile']);

or

this.router.navigate(['profile']);

or

this.router.navigate(['tabs(profile:profile)']);

and got this error :

Error: Cannot match any routes. URL Segment: ''

Answer

shivam gaddh picture shivam gaddh · Dec 3, 2018

Try:

this.router.navigate(['child component path'], {relativeTo: this.activatedRoute});

This solved my problem. Happy coding :)