title: How to add component dynamically through custom directive
body: <p>I want to write one custom directive, which will add component dynamically based on some logic inside the div, on which i've used my custom directive.  </p>
  
  <p>I tried using componentFactoryResolver and viewContainerRef.createComponent to add component dynamically</p>
  
  <pre><code>&lt;div myDirective&gt; 
     &lt;!-- dynamically add component through directive --&gt;
     &lt;span&gt;Hello&lt;/span&gt; 
  &lt;/div&gt;
  
  // my custom directive
  
  myDirective {
      constructor( private element: ElementRef,
          private renderer: Renderer,
          private viewContainerRef: ViewContainerRef,
          private componentFactoryResolver: ComponentFactoryResolver
      ) { }
  
      ngOnInit() {
          let componentFactory = this.componentFactoryResolver
                      .resolveComponentFactory(myComponent);
          let componentRef = this.viewContainerRef
                      .createComponent(componentFactory, 0);
      }
  
  }
  </code></pre>
  
  <p>Actual result: component is getting created after the div, 
  Expected: component should be added inside the div</p>