2个模块的角度动态分量声明

时间:2018-10-06 08:06:18

标签: angular

我尝试动态加载某些组件。因此,我以这种方式定义了我的“加载程序”组件

 @ViewChild('vc', {read: ViewContainerRef}) _container: ViewContainerRef;
 private componentRef: ComponentRef<{}>;

 constructor(
    private _compiler: Compiler,
    private _injector: Injector,
    private _m: NgModuleRef<any>
  ) {}

在我的模板中添加

<ng-template #vc></ng-template>

这是我加载动态组件的函数

compileTemplate() {

    let metadata = {
        selector: `runtime-component-sample`,
        template: `some html and some <app-foo></app-foo>`
    };

    if (this.componentRef) {
        this.componentRef.destroy();
        this.componentRef = null;
    }
    let factory = this.createComponentFactorySync(this._compiler, metadata, null);
    this.componentRef = this._container.createComponent(factory);
}

private createComponentFactorySync(compiler: Compiler, metadata: Component, componentClass: any): ComponentFactory<any> {

    var datas = someDatas;
    var parent = this;

    const cmpClass = componentClass || class RuntimeComponent {
      context: any = datas;
    };
    const decoratedCmp = Component(metadata)(cmpClass);

    @NgModule({ imports: [CommonModule,FontAwesomeModule], declarations: [decoratedCmp,FooComponent] })
    class RuntimeComponentModule { }

    let module: ModuleWithComponentFactories<any> = this._compiler.compileModuleAndAllComponentsSync(RuntimeComponentModule);
    return module.componentFactories.find(f => f.componentType === decoratedCmp);
}

当我回想compileTemplate时,出现此错误:

类型FooComponent是2个模块的声明的一部分:RuntimeComponentModule和RuntimeComponentModule!请考虑移动

我在执行createComponentFactorySync之前销毁了我的componentRef。这应该避免此错误

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我只添加:

compiler.clearCacheFor(FooComponent);