1

I recently upgraded my angular2 app to final version.

I tried to implement from lot of references provided online but got no success.

in angular2 RC5 , i used to load my components dynamically using compiler as below:

@Input('component-name') componentName: string;
@Input('component-model') componentModel: any;
@ViewChild('target', { read: ViewContainerRef }) target: ViewContainerRef;
private cmpRef: ComponentRef<any>;
public toSet: any;
keysRegister: string[] = [
    'BASIC-CAROUSEL',
    'BS-JUMBOTRON'
]
componentNames: string[]=[
    "BasicCarouselComponent",
    "BsJumbotronComponent"
]

constructor(private _compiler: Compiler, private _viewContainerRef:ViewContainerRef) { }

ngOnInit() {
    this.toSet={
      'componentModel':this.componentModel,
      'componentInfo':this.componentInfo
    };
}
ngAfterViewInit(): void {
    let componentIndex = this.keysRegister.indexOf(this.componentName);
    console.log(this.componentNames[componentIndex]);
    if (this.cmpRef) {
       this.cmpRef.destroy();
    }
    this._compiler.compileComponentAsync(StandardLib[this.componentNames[componentIndex]]).then(comp => {
        let ref = this.target.createComponent(comp);
        if (this.toSet) {
            const keys = Object.keys(this.toSet);
            keys.forEach(a => ref.instance[a] = this.toSet[a])
        }
    });
}
ngOnDestroy() {
    if (this.cmpRef) {
      this.cmpRef.destroy();
      this.cmpRef = null;
    }
}

where I set instance variable for the component using toSet . but as angular2 has been released this method has been deprecated. and I am not sure about how to get this done in angular2 final.

any inputs?

thanks in advance.

Bhushan Gadekar
  • 13,485
  • 21
  • 82
  • 131
  • 3
    Check this [How can I use/create dynamic template to compile dynamic Component with Angular 2.0?](http://stackoverflow.com/q/38888008/1679310) – Radim Köhler Sep 19 '16 at 10:03

1 Answers1

0

I am doing it like this:

System.import('path/to/MyComponent')
            .then(fileContents => fileContents['MyComponent'])
            .then(component => {
                let factory = this.componentFactoryResolver.resolveComponentFactory(component);
                this.container.createComponent(factory); //container: ViewContainerRef
            });
dstr
  • 8,362
  • 12
  • 66
  • 106
  • I am currently getting this error: Component xxx is not part of any NgModule or the module has not been imported into your module. Any ideas??? – Gerardlamo Oct 07 '16 at 11:01
  • @Gerardlamo: add your dynamically loaded compenent in NgModule's entryComponents list. – dstr Oct 07 '16 at 13:16