/**
 * reference: http://blog.rangle.io/dynamically-creating-components-with-angular-2/
 */ import { Component , Input , ViewContainerRef , ViewChild , ReflectiveInjector , ComponentFactoryResolver } from '@angular/core' ; import HelloWorldComponent from './hello-world-component' ; import WorldHelloComponent from './world-hello-component' ; @ Component ( { selector : 'dynamic-component' , entryComponents : [ HelloWorldComponent , WorldHelloComponent ] , template : `
        <div #dynamicComponentContainer></div>
  ` , } ) export default class DynamicComponent { currentComponent = null ; @ ViewChild ( 'dynamicComponentContainer' , { read : ViewContainerRef } ) dynamicComponentContainer : ViewContainerRef ; @ Input ( ) set componentData ( data ) { if ( ! data ) { return ; } let inputProviders = Object . keys ( data . inputs ) . map ( ( inputName ) => { return { provide : inputName , useValue : data . inputs [ inputName ] } ; } ) ; let resolvedInputs = ReflectiveInjector . resolve ( inputProviders ) ; let injector = ReflectiveInjector . fromResolvedProviders ( resolvedInputs , this . dynamicComponentContainer . parentInjector ) ; let factory = this . resolver . resolveComponentFactory ( data . component ) ; let component = factory . create ( injector ) ; this . dynamicComponentContainer . insert ( component . hostView ) ; if ( this . currentComponent ) { this . currentComponent . destroy ( ) ; } this . currentComponent = component ; } constructor ( private resolver ) { } }