lil-works
lil-works

Reputation: 710

angular dynamic component declarations of 2 modules

I try to load some component dynamically. So I define my "loader" component in this way

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

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

In my template I add

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

Here my function which load the dynamic component

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);
}

When I recall compileTemplate I get this error:

Type FooComponent is part of the declarations of 2 modules: RuntimeComponentModule and RuntimeComponentModule! Please consider moving

I destroy my componentRef before execute createComponentFactorySync. This should avoid this error

What I'm doing wrong?

Upvotes: 1

Views: 469

Answers (1)

lil-works
lil-works

Reputation: 710

I just add:

compiler.clearCacheFor(FooComponent);

Upvotes: 1

Related Questions