A short ‘how to’ inject the components dynamically in angular2.
1. we’ll start with the application component
2. the application will use a component (name it injector or container) which will inject dynamically other components (HeroComponent) passed by the application

In the AppComponent we define the list of components which should be injected:

injectableComponents: string[] = ['app-hero', 'wrong-component'];

In its template (app.component.html) we include the container (injector) which will inject dynamically required components defined in the property injectableComponents:

<app-container [componentsList]="injectableComponents"></app-container>

The ContainerComponent goes through the list of components which should be injected, checks if such components are registered in our application:


componentsList.forEach((item) => {
    let factory = factories.find((component:any) => {
        return component[1].selector === item;
    });

    //...
});

and if they are then the ContainerComponent injects them:


// if such component exists - inject it
if (factory) {
    let factoryClass = factory[0];
    // create the factory of the component which is going to be injected
    let componentFactory = this.resolver.resolveComponentFactory(factoryClass);
    // inject the component
    let cmpRef = this.widgetContainer.createComponent(componentFactory);

    // get the instance of the injected component
    let instance:any = cmpRef.instance;

    // using the component's instance, you have access to its scope,
    // so you can change any property (which is public) of it
    // let's change the title property of the injected component after a couple of second
    // to see the effect.
    setTimeout(() => {
        instance.title = 'New title defined by the injector component';
    }, 2000);

    console.log('The component ' + item + ' has been injected');
}
else {
    console.log('The component ' + item + ' doesn\'t exist');
}

Pay attention! All the components which are going to be injected dynamically should be listed in the entryComponents: [] property of the @NgModule({...}):


@NgModule({
    declarations: [
        AppComponent,
        ContainerComponent,
        HeroComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule
    ],
    providers: [ApiService],
    entryComponents: [HeroComponent], // <<=== HERE !!!!
    bootstrap: [AppComponent]
})

The source files of the project are here: https://github.com/t0w5a/ng2-dynamically-inject-components

The results:
ng2-dynamically-inject-components