title: Why is property not defined in angular using @ViewChild
body: <p>This is my component from where i'm trying to access a variable in a child component. The parent is the app component and the child is called LoginComponent</p>
  
  <pre><code>import { AfterViewInit, ViewChild } from '@angular/core';
  import { Component } from '@angular/core';
  import { LoginComponent } from './login/login.component';
  
  @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
  })
  export class AppComponent implements AfterViewInit {
  
      @ViewChild(LoginComponent)
      private loginComponent: LoginComponent;
      title = 'app';
  
      hideLogin(){
          this.loginComponent.displayPopover = 'none';
      }
  
  }
  </code></pre>
  
  <p>I took this code from this example in the <a href="https://angular.io/guide/component-interaction#parent-calls-an-viewchild" rel="nofollow noreferrer" title="angular.io sitequot;">angular.io site</a> 
  The problem is that when the hideLogin() function is executed i get this error: </p>
  
  <pre><code>TypeError: this.loginComponent is undefined
  Stack trace:
  AppComponent.prototype.hideLogin@webpack-internal:///../../../../../src/app/app.component.ts:21:9
  View_AppComponent_0/&lt;@ng:///AppModule/AppComponent.ngfactory.js:10:23
  viewDef/handleEvent@webpack-internal:///../../../core/esm5/core.js:13777:115
  ...
  </code></pre>
  
  <p>I truncated the error message because i don't think the whole stack trace is of any use.
  Anyhow, i think the error may be that the loginComponent object is not initialized. But it sound weird to me that the message says "is not defined" and in the example i took it from, it doesn't do anything to initialize the object and somehow it's seems like it has assigned the instance of the component's singleton since it's accessing its properties.</p>
  
  <p>This problem is differen from that in the <a href="https://stackoverflow.com/questions/40299808/viewchild-return-undefined">@viewChild return undefined</a> issue since i'm not trying to access the object from the constructor. I'm trying to access it from a function that is executed via a click event. Here'e my app component view:</p>
  
  <pre><code>&lt;div (click)="hideLogin()"&gt;
  &lt;app-top-bar&gt;&lt;/app-top-bar&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>I even tried accessing it from the ngAfterViewInit() method like this:</p>
  
  <pre><code>ngAfterViewInit(){
      this.loginComponent.displayPopover = 'none';
  }
  </code></pre>
  
  <p>But i get the same exact error</p>