angularroutesangular-routingangular-libraryangular19

Angular Library Routing Not Working When Used Inside Angular 19 App


I'm working on an Angular 19 app that uses a custom Angular library, and I'm having trouble getting the routing inside the library to work properly. The app is a legacy app and all the components are Non-Standalone

The main **app-routing**

    const routes: Routes = [
    {
        path: 'layout',
        component: Container,
        children: [
            { path: 'property/:id', component: PropertyContainerComponent},
            { path: 'portfolio/:id', component: PortfolioContainerComponent}
        ]
    }
]

inside PropertyContainerComponent & PortfolioContainerComponent

<lib-component [input]="data"></lib-component>

Library Routing - The library defines its own internal routes using RouterModule.forChild():

   const routes: Routes = [
      { path: 'projects', component: ProjectsComponent },
      { path: 'dashboard', component: DashboardComponent }
    ];
  
   @NgModule({
    declarations: [],
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]})

library module:

@NgModule({
  imports: [CommonModule, RouterModule.forChild(routes)],
  declarations: [ProjectsComponent, DashboardComponent],
})
export class LibModule {}

Library Component I am checking if the parent route property or portfolio and navigating accordingly

 if (property)
      this.router.navigate(['projects'], { relativeTo: this.route });
    if (portfolio)
      this.router.navigate(['dashboard'], { relativeTo: this.route });

The Issue - When I navigate to the library from the app:

layout/property/100/projects
layout/portfolio/100/dashboard

The URL forms correctly, but I get an error:

NG04002: Cannot match any routes. URL Segment: 'layout/property/100/projects'

What I’m Trying to Achieve

I want the library to handle its own internal routing (like /projects and /dashboard), mounted under a parent route in the app (e.g. layout/property/:id/...).


Solution

  • You have to specify the child routes using the module (use loadChildren), we can use lazy loading as an additional enhancement.

    const routes: Routes = [
    {
        path: 'layout',
        component: Container,
        children: [
            {  
              path: 'property/:id',  
              component: PropertyContainerComponent, 
              loadChildren: () => import('./<path to lib module>/lib-routing.module').then(m => m.routes)
            },
            {  
              path: 'portfolio/:id',  
              component: PortfolioContainerComponent, 
              loadChildren: () => import('./<path to lib module>/lib-routing.module').then(m => m.routes)
            }
        ]
    }
    

    Also ensure either PropertyContainerComponent or lib-component has a <router-outlet></router-outlet> inside them, so that the child route can be rendered.