Can you please advice me how to handle the situation where I have in a high level component router-outlet
and in its sub component another router-outlet
?
It seems to me that in this scenario I need to have the sub component in its own module and to provide for it its own router using the RouterModule.forChild
. After the configuration I can display the main component on localhost:4200/main
, but I get this error when going to localhost:4200/main/section
:
Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'main/section'
I have in the app.component.html:
<router-outlet></router-outlet>
In this app.component.html
I want to display MainViewComponent
under localhost:4200/main
This MainViewComponent component is in its own module has its own logic to display its subcomponents in its <router-outlet></router-outlet>
and should be accessible through an url like localhost:4200/main/section
, localhost:4200/main/section2
.
app/app-routing.module.ts (imported by app.module.ts )
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MainViewComponent } from './main-view-module/main-view/main-view.component';
const routes: Routes = [
{ path: '', redirectTo: 'main', pathMatch: 'full' },
{ path: 'main', component: MainViewComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [ RouterModule ]
})
export class AppRoutingModule { }
app/main-view-module/app-routing.module.ts (imported by app/main-view-module/main-view.module.ts)
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { SectionViewComponent } from './main-view-module/section-view.component';
import { Section2ViewComponent } from './main-view-module/section2-view.component';
const routes: Routes = [
{ path: '', redirectTo: 'section', pathMatch: 'full' },
{ path: 'section', component: SectionViewComponent },
{ path: 'section2', component: Section2ViewComponent }
];
@NgModule({
imports: [
RouterModule.forChild(routes)
],
exports: [ RouterModule ]
})
export class AppRoutingModule { }
After additional research:
The feature that I look for is called Lazy loading.
In order to make my example work I just had to add loadChildren
property to the path
in my app/app-routing.module.ts
:
const routes: Routes = [
{ path: '', redirectTo: 'main', pathMatch: 'full' },
{ path: 'main', component: MainViewComponent,
loadChildren: 'app/main-view-module/main-view.module#MainViewModule'
}
];