title: Dynamically create a component inside an ngIf
body: <p>I am using Angular 6 and I've tried following the answer <a href="https://stackoverflow.com/questions/40811809/add-component-dynamically-inside-an-ngif">here</a> but I can't get it to work</p>
  
  <pre><code>export class AppComponent implements AfterContentInit, AfterViewInit {
    defaultToTrue = true;
    @ViewChildren('parent', { read: ViewContainerRef }) parent: QueryList&lt;ViewContainerRef&gt;;
  
    constructor(private cfr: ComponentFactoryResolver) { }
  
    ngAfterViewInit(){
      const resolve = this.cfr.resolveComponentFactory(ChildComponent);
      this.parent.changes.subscribe(changes =&gt; {
        this.parent.createComponent(resolve); //Error
      });
    }
  
  }
  </code></pre>
  
  <p>HTML:</p>
  
  <pre><code>&lt;div *ngIf="defaultToTrue"&gt;
    &lt;div #parent&gt;&lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p><a href="https://stackblitz.com/edit/angular-yvxn6w" rel="nofollow noreferrer"><strong>StackBlitz</strong></a></p>