Bill
Bill

Reputation: 2352

Nested routing in Angular 5

I have the following module structure:

1- RootModule

With routing as follows:

const routes: Routes = [
  { path: '', redirectTo: 'app', pathMatch: 'full' }
];

2- AppModule

With routing as follows:

const routes: Routes = [
   { 
        path: 'app', 
        component: AppComponent,
        children: [
            {
                path: '',
                redirectTo: 'index',
                pathMatch: 'full'
           }
       ]
   }

];

Also, AppModule imports MainModule which is only a routing module and is configured as follows:

const routes: Routes = [
    {
        path: '',
        component: MainComponent,
        children: [
            {
               path: 'index',
               loadChildren: '.\/..\/modules\/index\/index.module#IndexModule'
            },
            {
                path: '',
                redirectTo: 'index',
                pathMatch: 'full'
            }
       ]
  }

];

Now, RootComponent is the starting point:

@Component({
  selector: "app-root",
  template:  "<router-outlet></router-outlet>"
})
export class RootComponent implements OnInit {
  constructor() { }

  ngOnInit() {
 }
}

The AppComponent is defined as:

<router-outlet></router-outlet>
<app-quick-sidebar></app-quick-sidebar>

Finally, MainComponent is defined as:

<app-header-nav></app-header-nav>
<router-outlet></router-outlet>
<app-footer></app-footer>

The whole point is to route the application to /index component in such a way to pass through RooComponent --> AppComponent --> MainComponent --> IndexComponent

So far, with the above routes, AppComponent is bypassed!

Any idea?

Thanks

Upvotes: 8

Views: 5923

Answers (1)

Tomasz Kula
Tomasz Kula

Reputation: 16837

With your current routes configuration, MainComponent is not configured in the children array of AppComponent's path. So why would it appear in its template?

Right now you routing configuration will work like this:

  • navigating to /app will get you to AppComponent
  • navigating to /index will get you to the IndexComponent.

To achieve the desired behavior of RooComponent --> AppComponent --> MainComponent --> IndexComponent, your routes configuration should look like this:

const routes: Routes = [{ 
  path: '', 
  component: AppComponent,
  children: [{
    path: '',
    component: MainComponent,
    children: [{
      path: '', redirectTo: 'index', pathMatch: 'full'
    }, {
      path: 'index',
      loadChildren: '.\/..\/modules\/index\/index.module#IndexModule'
    }]
  }]
}];

Upvotes: 4

Related Questions