title: Angular - ViewChild(Directive) returns undefined in Directive
body: <p>Angular V7.x</p>
  
  <p>I am creating a Directive that adds a dynamic component to the specified container. I am using another Directive to mark as an insertion point but, ViewChild() returns undefined no matter what. Even if it's accessed in <code>ngAfterViewInit</code>. Angular Docs example accesses ViewChild in <code>ngOnInit</code>, though.</p>
  
  <p><strong>alert.directive.ts</strong></p>
  
  <pre><code>import { Directive, ViewChild, TemplateRef, ViewContainerRef, Input } from '@angular/core';
  import { AlertHostDirective } from './alert-host.directive';
  
  @Directive({
    selector: '[appAlert]'
  })
  export class AlertDirective {
    @ViewChild(AlertHostDirective) alertHost;
  
    constructor(
      private templateRef: TemplateRef&lt;any&gt;,
      private viewContainer: ViewContainerRef
    ) {}
  
    ngAfterViewInit() {
      console.log(this.alertHost); // undefined
    }
  
    ngOnInit() {
      console.log(this.alertHost); // undefined
    }
  
    @Input() set appAlert(name: string) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    }
  }
  </code></pre>
  
  <p><strong>alert-host.directive.ts</strong></p>
  
  <pre><code>import { Directive } from '@angular/core';
  
  @Directive({
    selector: '[appAlertHost]'
  })
  export class AlertHostDirective {
  
    constructor() { }
  
  }
  </code></pre>
  
  <p><strong>form-signup.html</strong></p>
  
  <pre><code>&lt;form *appAlert="'signupForm'" class="form-signup" (submit)="onSubmit($event)" [formGroup]="signupForm"&gt;
        &lt;h2 class="mb-4"&gt;Sign Up &amp;mdash; it's free&lt;/h2&gt;
        &lt;ng-template appAlertHost&gt;&lt;/ng-template&gt;
        ... (more content)
  &lt;/form&gt;
  </code></pre>
  
  <p>StackBlitz Link: <a href="https://stackblitz.com/edit/angular-wizxcc" rel="nofollow noreferrer">VIEW ON STACKBLITZ</a></p>