Search code examples
angularlazy-loadingangular-routing

Angular nested Routing in lazy loading Modules with router-outlet name


I am trying to use nested routing together with a named router-outlet to accomplish routing for my side-bar navigation.
I have a main module that loads the nav-component which has a named router-outlet in it's template:

<router-outlet name="content"></router-outlet>

Now I have multiple nav-links that use the router-link directive to link for example to: http://localhost:4200/ticket:

<a routerLink="ticket">New Ticket</a>

The routing definition for this module is in the module itself:

#main.module.ts

const routes: Routes = [
  { path: '', component: NavComponent, children: [
    { path: 'ticket', component: NewTicketComponent, outlet: 'content' }
  ]},
]

@NgModule({
  declarations: [NavComponent, NewCustomerDialogComponent, NewTicketComponent],
  imports: [
    CommonModule,
    RouterModule.forChild(routes),
  ]
})
export class MainModule { }

So when you navigate to: localhost:4200/ticket I want the NavComponent visible and the NewTicketComponent to be inserted into the named router-outlet

This is what my app-routing.module.ts looks like:

#app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginModule } from './login/login.module';

const routes: Routes = [
  { path: 'login', loadChildren: () => import('./login/login.module').then(m => m.LoginModule) },
  { path: '', loadChildren: () => import('./main/main.module').then(m => m.MainModule) },
  // { path: '**', redirectTo: 'login' }
];

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

I am getting the following error:

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


Solution

  • I managed to get it working using nested router-outlets without naming them.

    I simply made a <router-outlet></router-outlet> element in my NavComponent template. Then I simply defined the nested route like this:

    #main.module.ts
    const routes: Routes = [
      { path: 'main', component: NavComponent, children: [
        { path: 'ticket/new', component: NewTicketComponent}
      ]},
    ];