Angular2 - 从模块动态加载组件

时间:2016-09-02 16:42:32

标签: dynamic angular typescript

在我的角度应用程序中,我有以下内容:

export class MyComponent {
    subcompPath = "path-to-subcomp#SubcompClassName";
    @ViewChild("placeholder", { read: ViewComponentRef }) placeholderRef: ViewComponentRef;

/* Constructor where Compiler, ComponentFactoryResolver are injected */

    loadSubcomponent() {
        let [path, componentName] = this.subcompPath.split("#");
        (<any>window).System.import(path)
            .then((module: any) => module[componentName])
            .then((type: any) => {
                return this._compiler.compileComponentAsync(type)
            })
            .then((factory: any) => {
                let componentRef = this.placeholderRef.createComponent(factory, 0);
            });
    }
}

我的子组件声明了提供者和东西,指令和管道。

现在RC6又打破了一切。组件不能声明指令和管道,但它们必须位于声明组件的模块中。 所以我必须加载SystemJS而不是组件本身而是模块。 好的,然后我应该使用

return this._compiler.compileModuleAndAllComponentsAsync(type)

很好,但是如何获得该特定组件的工厂参考?那个工厂就是我所需要的,placeholderRef想要它的createComponent方法,对吗?

我试图从github挖掘angular2源代码,但是它非常庞大,我应该尝试使用VS Code或其他东西,使用intellisense,但是我很懒...我应该读这个文档中的东西,对于这个特殊的参数,在angular.io中是相当乏味的,这是没有路由器的组件和模块的延迟加载。

感谢任何帮助,我认为解决方案很容易应用,但如果没有官方文档很难找到。

2 个答案:

答案 0 :(得分:9)

<强>更新

如果你想与编辑一起使用它,你应该手动提供像

这样的编译器
export function createJitCompiler () {
   return new JitCompilerFactory([{useDebug: false, useJit: true}]).createCompiler();
}
...
providers: [
  { provide: Compiler, useFactory: createJitCompiler}
],

<强> Example

旧版

它可能会对您有所帮助:

this.compiler.compileModuleAndAllComponentsAsync(DynamicModule)
      .then(({moduleFactory, componentFactories}) => {
        const compFactory = componentFactories
           .find(x => x.componentType === DynamicComponent);
        const cmpRef = this.placeholderRef.createComponent(compFactory, 0);

另见

答案 1 :(得分:8)

根据yurzui的回答,我来到以下代码:

export class MyComponent {
    subcompPath = "path-to-subcompMODULE#SubcompClassName";
    @ViewChild("placeholder", { read: ViewComponentRef }) placeholderRef: ViewComponentRef;

    /* Constructor where Compiler, ComponentFactoryResolver are injected */

    loadSubcomponent() {
        let [modulePath, componentName] = this.subcompPath.split("#");
        (<any>window).System.import(modulePath)
            .then((module: any) => module["default"])  // Or pass the module class name too
            .then((type: any) => {
                return this._compiler.compileModuleAndAllComponentsAsync(type)
            })
            .then((moduleWithFactories: ModuleWithComponentFactories<any>) => {
                const factory = moduleWithFactories.componentFactories.find(x => x.componentType.name === componentName); // Crucial: componentType.name, not componentType!!
                let componentRef = this.placeholderRef.createComponent(factory, 0);
            });
    }
}