0

I have created an Application with a Component Library. My library contains routes. When I try to lazy load the library into the application I use the following route:

const routes: Routes = [
  { path: 'test2', loadChildren: () => import('my-lib' ).then(x => x.MyLibModule) },
];

I import that route into my AppRoutingModule for the application:

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

In the library module MyLibModule I define my library routes and import them using the forChild method

imports: [
   ...
   RouterModule.forChild(routerConfig),
   ...
 ],

This works for my default route. If you navigate to the base route "localhost:4200/test2" the library's default route correctly loads. However, when a button is clicked and another route is navigated to, the 'test2' base of the library's routes is removed. The page "localhost:4200/page2" loads instead of "localhost:4200/test2/page2". That url doesn't exist and I get an error. However if you navigate to "localhost:4200/test2/page2", the correct page loads.

What is happening to the 'test2' base url on redirect? How do I maintain this base url without changing code in my library?

afriedman111
  • 1,925
  • 4
  • 25
  • 42

1 Answers1

0

Update 12/13/19 - use relativeTo

1) Inject ActivatedRoute in your component constructor.

constructor(private router: Router, private route: ActivatedRoute) { }

2) Router.navigate() accepts a second parameter of type NavigationExtras. Set the relativeTo property using the injected route.

this.router.navigate(['child'], {relativeTo: this.route});

StackBlitz demo

Chris Newman
  • 3,152
  • 1
  • 16
  • 17