Bhushan Gadekar Bhushan Gadekar - 2 months ago 9
TypeScript Question

loading components dynamically in angular2 final?

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.

Answer

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