Hyune
Hyune

Reputation: 31

Angular 5 loadChildren route from modules -> No NgModule metadata found

I use the following tools:

In my Angular 5 main app i have a CoreModule and a DashboardModule. In the CoreModule i have the following route:

import {RouterModule, Routes} from "@angular/router";
import {NgModule} from "@angular/core";
import {LoginComponent} from "./login/login.component";
import {AuthGuardService} from "./services/auth-guard.service";

const routes: Routes = [
  {
    path: '',
    component: LoginComponent
  },
  {
    path: 'dashboard',
    canActivate: [AuthGuardService],
    loadChildren: '@modules/dashboard/dashboard.module#DashboardModule'
  }
];

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

export class CoreRoutingModule {}

It's ok when i work in my main application, but if i pack CoreModule and DashboardModule in a lib with ng-packagr when i used them in another application as NPM package i got the following error at startup:

ERROR in No NgModule metadata found for 'DashboardModule'.

Any ideas ?

Upvotes: 3

Views: 2081

Answers (1)

user2434945
user2434945

Reputation: 13

UPDATE

Angular now supports lazy load modules outsite src folder. You should use the lambda syntax (that is a pattern now) and JS imports.

const routes: Routes = [
  {
    path: '',
    loadChildren: async () => (await import('./sdk/sdk.module')).SdkModule
  },
  {
    path: 'layouts',
    loadChildren: () => import('@my-lib/layouts').then(m => m.LayoutModule)
  }
];

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

Old Answer

I'm having same problem. This is an open issue on Angular-cli. Angular-cli can't (unitl today) 'lazy load' modules outside src folder. In other words, you can't lazy load from node_modules.

There is an open issue explaining the problem and a work arround.

https://github.com/angular/angular-cli/issues/6373

The work arround is wrap your lazy module in other local module, and than, import the local module as lazy module. The problem is you shall create a proxy-module for each "external" module ;/ Another problem is you can't have 'Lazy Modules' inside your external package.

dashboard-proxy.module.ts

    @NgModule({
      imports: [
        CommonModule,
        DashboardModule <<---- External Module @pkg/admin/dashboard
      ],
      exports: [
        DashboardModule
      ],
      declarations: []
    })
export class DashboardProxyModule { }

proxy-router-routing-module.ts

const routes: Routes = [
  {
    path: 'dashboard',
    loadChildren: 'app/proxy-router/dashboard-proxy/dashboard-proxy.module#DashboardProxyModule' << ---- Proxy
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class ProxyRouterRoutingModule { }

Upvotes: 1

Related Questions