Search code examples
dynamicangularangular-module

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 ?


Solution

  • 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.