title: How to load dynamically a component in angular 4 in the parent component
body: <p>I'm creating template components to be loaded in the parent component depending on what response I get from the server. I'll give you a brief example of what I'm trying to do in pseudo code. </p>
  
  <p>This is my html parent component:</p>
  
  <pre><code>&lt;div class="parent-container"&gt;
      &lt;div *ngIf="template1"&gt; (load template1.component) &lt;/div&gt;
      &lt;div *ngIf="template2"&gt; (load template2.component) &lt;/div&gt;
      etc...
  &lt;/div&gt;
  </code></pre>
  
  <p>then I would have the different components (for sake of brevity I will just list one) </p>
  
  <pre><code>&lt;div class="child-container"&gt;
      &lt;div&gt; {{userName}} &lt;/div&gt;
      &lt;div&gt; {{contactNo}} &lt;/div&gt;
      &lt;div&gt; {{address}} &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>so on ngInit the parent makes an http request to the server and gets a value. Depends on the value in the parent, I should be able to load the child template into the parent and display it. So, once loaded, the page would look like this:</p>
  
  <pre><code>&lt;div class="parent-container"&gt;
      &lt;div class="child-container"&gt;
          &lt;div&gt; {{userName}} &lt;/div&gt;
          &lt;div&gt; {{contactNo}} &lt;/div&gt;
          &lt;div&gt; {{address}} &lt;/div&gt;
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>Is it possible in angular? How can i create it?
  Thanks</p>
  
  <p>[<strong>edit</strong>]</p>
  
  <p>I implemented what dee zg suggested, this is the code: </p>
  
  <pre><code>@ViewChild(HostDirective) host: HostDirective;
  
  OnNgInit(){}
  
  //switch will be a response from a server 
  selector(switch){
      switch(switch) { 
         case 'component1': { 
           this.loadComponent(Component1);
           break; 
        }  
        default: { 
  
           break; 
        } 
     } 
  
    }
  
    loadComponent(component){   
  
  
      var componentFactory = this._componentFactoryResolver.resolveComponentFactory(component);
      var viewContainerRef = this.host;
      this.viewContainerRef.clear();
      var componentRef = this.viewContainerRef.createComponent(componentFactory);
  
      (componentRef.instance);
  
    }
  </code></pre>
  
  <p>this is what is inside my host</p>
  
  <pre><code>import { Directive, ViewContainerRef } from '@angular/core';
  
  @Directive({
    selector: '[host]',
  })
  export class HostDirective {
    constructor(public viewContainerRef: ViewContainerRef) { }
  }
  </code></pre>
  
  <p>and the html </p>
  
  <pre><code>&lt;ng-template host&gt;&lt;/ng-template&gt;
  </code></pre>
  
  <p>funny thing is that if whatever is inside loadComponent will be loaded into OnInit, then it will work. If I call it from loadComponent I will get that host is undefined. </p>