title: Angular 8 @ViewChild returns undefined. Can't access ElementRef
body: <p>I am trying to access elements in my template in <code>component</code>. I added references to elements. I can access these elements inside template but in component code when I get references with <code>@ViewChild</code> they return <code>undefined</code>.</p>
  
  <p>Here is my template code.</p>
  
  <pre><code>&lt;a #cartMenuButton class="nav-link cart-menu-button" (click)="cartMenuClick($event)"&gt;
      &lt;i class="fas fa-shopping-cart"&gt;&lt;/i&gt;&amp;nbsp;{{getCartCount()}}&lt;/a&gt;
  
  
  &lt;div #cartMenuContainer class="cart-menu-container" (click)="cartMenuContainerClick($event)"
      [style.display]="cartMenuVisible?'block':'none'"&gt;
  
      &lt;div #cartMenu class="cart-menu" [style.left.px]="cartMenuButton.offsetLeft-240"
          [style.top.px]="cartMenuButton.offsetTop+cartMenuButton.offsetHeight"&gt;
  
          &lt;div class="cart-menu-items bg-light"&gt;
  
              &lt;ul class="list-group"&gt;
  
                  &lt;app-cart-menu-item class="list-group-item bg-light" *ngFor="let item of sessionService.getCart()"
                      [item]="item"&gt;
  
                  &lt;/app-cart-menu-item&gt;
              &lt;/ul&gt;
          &lt;/div&gt;
  
          &lt;div class="cart-menu-footer bg-dark"&gt;
              &lt;a routerLink="/cart" class="text-light float-left"&gt;Go to cart&lt;/a&gt;
              &lt;a class="text-light float-right"&gt;Clear cart&lt;/a&gt;
          &lt;/div&gt;
  
      &lt;/div&gt;
  
  &lt;/div&gt;
  </code></pre>
  
  <p>Here is my component.</p>
  
  <pre><code>import { Component, ViewChild, ElementRef } from '@angular/core';
  import { SessionService } from '../../../../services/session.service';
  
  @Component({
      selector: 'app-cart-menu',
      templateUrl: 'cart-menu.component.html',
      styleUrls: ['cart-menu.component.scss']
  })
  export class CartMenuComponent {
  
      public cartMenuVisible: boolean = false;
  
      @ViewChild('cartMenuButton', { read: Element, static: false })
      public cartMenuButton: ElementRef;
  
      @ViewChild('cartMenuContainer', { read: Element, static: false })
      public cartMenuContainer: ElementRef;
  
      constructor(public sessionService: SessionService) {
      }
  
      getCartCount(): number {
          var count = this.sessionService.getCart() ? this.sessionService.getCart().reduce((acc, cur) =&gt; acc + cur.count, 0) : 0;
          return count;
      }
  
      cartMenuClick(event: MouseEvent) {
          this.cartMenuVisible = true;
      }
  
      cartMenuContainerClick(event: MouseEvent) {
          if (event.currentTarget === this.cartMenuContainer.nativeElement)
              this.cartMenuVisible = false;
      }
  }
  </code></pre>
  
  <p>In <code>cartMenuContainerClick</code> function it <code>this.cartMenuContainer</code> returns <code>undefined</code>.</p>