Angular 4 Lazy loading with named router-outlet not working
This is known bug, you can track the issue here
The workaround or we can say solution to this issue is, use non-empty paths for your top level routes if auxilary(i.e. named) routes exist in a lazy loaded module.
The only flaw I can see is, an additional url segment added in routes
MainRoutingModule: Top level non-empty path(i.e. "path: 'load'")
import { ModuleWithProviders, NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MainpageComponent } from './mainpage.component';
import { ProductComponent } from './product.component';
import { ProductDetailComponent } from './productdetail.component';
const childroutes: Routes = [
{ path: 'load', component: MainpageComponent ,
children: [
{path: 'product', component: ProductComponent
{path: 'productdetail', component: ProductDetailComponent,
outlet: 'detail'
},
]
},
];
export const routing: ModuleWithProviders = RouterModule.forChild(childroutes);
const newLocal: NgModule = {
imports: [RouterModule.forChild(childroutes) ],
exports: [RouterModule, ],
declarations: []
};
@NgModule(newLocal)
export class MainRoutingModule { }
MainpageComponent:The correct syntax to use the secondary routes.
[routerLink]="[{outlets:{detail:['productdetail']}}]"
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-main',
template: `
<div>
<div><a [routerLink]="['product']"> Product </a> </div>
<div><a [routerLink]="[{outlets:{detail:['productdetail']}}]"> Product Detail </a> </div>
<div> <router-outlet></router-outlet></div>
<div> <router-outlet name="detail"></router-outlet>
</div>
`,
encapsulation: ViewEncapsulation.None,
})
export class MainpageComponent {}
LoginComponent:
Use [routerLink]="['mainpage/load']" to load the main module.
import { Component, OnInit, OnDestroy } from '@angular/core';
@Component({
selector: 'app-login',
template: `This is login page place holder <br> <a [routerLink]="['mainpage/load']">Go to Main Page</a>`,
})
export class LoginComponent implements Oninit, OnDestroy {
constructor() {}
ngOnInit(): void {}
}
Demo:https://plnkr.co/edit/0ZpNL3lvbRbexLzQqRZh?p=preview