Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Lazy loading a NgModule in a NPM module with angular router

I have been lazy loading modules in routes e.g.

export const HomeRoute: Route = {
  path: '',
  component: HomeComponent,
  canActivate: [AuthGuard],
  children: [
    {path: 'dashboard', loadChildren: 'app/+dashboard/db.module#DashboardModule'}
  ]
};

I would like to put my "pages" into NPM modules. What is the route to the node_module that I should use in the loadChildren attribute? I am using angular-cli 1.0.0-beta.16

I have tried

{path: 'lazy', loadChildren: '../node_modules/hello-world/components#HelloWorld' }

also

{path: 'lazy', loadChildren: 'hello-world/components#HelloWorld' }

The exported class is: -

import {Component} from '@angular/core';

@Component({
    selector: 'hello-world',
    styles: [`
       h1 {
            color: blue;
        }
    `],
    template: `<div>
                  <h1 (click)="onClick()">{{message}}</h1>
               </div>`
})
export class HelloWorld {

    message = "Click Me ...";

    onClick() {
        this.message = "Hello World!";
        console.log(this.message);

    }
}

Is there anything else I should try?

like image 203
Ash McConnell Avatar asked Oct 06 '16 14:10

Ash McConnell


People also ask

How do you do lazy loading in Angular 2?

To lazy load Angular modules, use loadChildren (instead of component ) in your AppRoutingModule routes configuration as follows. content_copy const routes: Routes = [ { path: 'items', loadChildren: () => import('./items/items. module'). then(m => m.

Which router module is used for lazy loading?

Create a Module with Routingmodule. ts, which is one of the files needed to set up lazy loading for your feature module. Navigate to the project by issuing the cd client-app command. The --routing option used Angular/CLI version 8.1 or higher.

What is needed to set up a lazy loaded feature module in Angular?

Step 1 – Setting Up the Project Lazy loaded routes need to be outside of the root app module. You will want to have your lazy loaded features in feature modules. First, let's use Angular CLI to create a new project with Angular Router: ng new angular-lazy-loading-example --routing --style=css --skip-tests.


1 Answers

This currently isn't possible - see a response from the AngularJS CLI team here: -

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

"This is a very relevant question. I don't think we support it in the CLI atm." (Currently version beta 17)

Datumgeek has implemented lazy loading from modules in a different way (outside of CLI) here: - https://github.com/datumgeek/a2dyn/blob/master/README.md#development-server

I will update the answer if it becomes possible in the Angular CLI in the future

like image 131
Ash McConnell Avatar answered Nov 15 '22 01:11

Ash McConnell