4

in angular website there is new api SystemJsNgModuleLoader .

dose anyone know how can i use this api to load dynamic module in the app ?

Mehran Mazhar
  • 63
  • 3
  • 13
  • See http://stackoverflow.com/questions/40293240/how-to-manually-lazy-load-a-module and http://stackoverflow.com/questions/41171593/how-to-lazy-load-angular-2-components-in-a-tabview-primeng/41178949#41178949 – yurzui Feb 17 '17 at 09:46

2 Answers2

2

i know you would have found the solution, but for the reference of others i'm providing the solution. The code has been well commented and its well understandable.

createComponent(fileName, componentName){
    let injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
    // 1. Create module loader
    let loader = new SystemJsNgModuleLoader(this.compiler);
    loader.load(fileName).then((nmf:NgModuleFactory<any>)=>{
        // 2. create NgModuleRef
        let ngmRef = nmf.create(injector);
        // 3. Create component factory
        let cmpFactory = ngmRef.componentFactoryResolver.resolveComponentFactory( componentName );
        // 4. Create the component
        let componentRef = this.span.createComponent(cmpFactory,0,injector,[]);
        // 5. Init the component name field.
        componentRef.instance.name = "Some Name";
        // 6. Refresh the component area.
        componentRef.changeDetectorRef.detectChanges();
        componentRef.onDestroy(()=> {
            componentRef.changeDetectorRef.detach();
        });
    });
}

By using the above function, we could inject a module from any source. For futher please refer this.

Mohan Rex
  • 1,674
  • 2
  • 17
  • 22
0

I have found few examples of using SystemJsNgModuleLoader.

Angular2 + loading dynamically module and component from path. : https://embed.plnkr.co/khdS8xFkvqe7ZIsz0kc7/

Angular2 + SystemJsNgModuleLoader test : https://embed.plnkr.co/mgdBhKpCVI1LRQ2l81pC/

Dynamically importing modules at Runtime: https://myview.rahulnivi.net/dynamically-importing-modules-runtime/

Another way of lazy loading external libraries: https://github.com/angular/angular-cli/issues/6373

Lazy loading of feature library modules from node_modules: https://github.com/angular/angular/issues/25083

Why And How To Lazy Load Angular Libraries : https://medium.com/@tomastrajan/why-and-how-to-lazy-load-angular-libraries-a3bf1489fe24

I hope this will be helpful.

Thanks, Jignesh Raval

Jignesh Raval
  • 587
  • 7
  • 15