Mehran Mazhar
Mehran Mazhar

Reputation: 63

how can i use "SystemJsNgModuleLoader" in angular 2 to import dynamic modules to app?

in angular website there is new api SystemJsNgModuleLoader .

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

Upvotes: 4

Views: 3900

Answers (2)

Jignesh Raval
Jignesh Raval

Reputation: 607

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

Upvotes: 0

Mohan Rex
Mohan Rex

Reputation: 1674

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.

Upvotes: 2

Related Questions