Bhushan Gadekar Bhushan Gadekar - 1 year ago 67
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[] = [
componentNames: string[]=[

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

ngOnInit() {
ngAfterViewInit(): void {
let componentIndex = this.keysRegister.indexOf(this.componentName);
if (this.cmpRef) {
this._compiler.compileComponentAsync(StandardLib[this.componentNames[componentIndex]]).then(comp => {
let ref =;
if (this.toSet) {
const keys = Object.keys(this.toSet);
keys.forEach(a => ref.instance[a] = this.toSet[a])
ngOnDestroy() {
if (this.cmpRef) {
this.cmpRef = null;

where I set instance variable for the component using
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 Source

I am doing it like this:

            .then(fileContents => fileContents['MyComponent'])
            .then(component => {
                let factory = this.componentFactoryResolver.resolveComponentFactory(component);
                this.container.createComponent(factory); //container: ViewContainerRef
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download