Search code examples
angularangular6angular-routerangular-routerlink

Router navigate to child route - Angular 6


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: ''


Solution

  • I found solution by adding profile path below '' and 'tabs' path:

      {
        path: 'profile',
        redirectTo: '/tabs/(profile:profile)',
        pathMatch: 'full'
      }
    

    Now I am able to navigate to profile with

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

    I forgot to add this path in tabs.router.module.ts. Because of that I was getting mentioned error