Cannot read property 'viewContainerRef' of undefined : <p>I am trying to display a dynamic component similar (not exact) to the example in angular docs.</p>

<p>I have a dynamic directive with viewContainerRef</p>

<pre><code>@Directive({
   selector: '[dynamicComponent]'
})
export class DynamicComponentDirective {
   constructor(public viewContainerRef: ViewContainerRef) { }
}
</code></pre>

<p>Excerpt from component code</p>

<pre><code>@ViewChild(DynamicComponentDirective) adHost: DynamicComponentDirective;
..
ngAfterViewInit() {
let componentFactory = null;
                console.log(component);
                componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
                // this.adHost.viewContainerRef.clear();
                const viewContainerRef = this.adHost.viewContainerRef;
                viewContainerRef.createComponent(componentFactory);
}
</code></pre>

<p>Finally added <code>&lt;ng-template dynamicComponent&gt;&lt;/ng-template&gt;</code> in template</p>
