title: TypeError: Cannot read property 'nativeElement' of undefined Angular 8
body: <p>problem</p>
  
  <blockquote>
    <p>TypeError: Cannot read property 'nativeElement' of undefined</p>
  </blockquote>
  
  <p>component1</p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;div id="formkeyRefId" #formkeyRefId (click)="test.reloadContent(data.value)&gt; &lt;/div&gt;
  &lt;ng-container&gt;
      &lt;app-component2  #test [data]="data.value" &gt;&lt;/app-component2&gt;
  &lt;/ng-container&gt;
  &lt;/div&gt;
  </code></pre>
  
  <pre><code>           export class Component1 implements OnInit, AfterViewInit {
  
              @ViewChild('formkeyRefId', { static: false }) formkeyRefId: ElementRef;
  
              constructor() { }
  
              ngOnInit() { }
  
  
              ngAfterViewInit() {
  
                  console.log(this.formkeyRefId.nativeElement);
                  this.formkeyRefId.nativeElement.click();
                  setTimeout(() =&gt; {
                      console.log(this.formkeyRefId.nativeElement.id);
                      this.formkeyRefId.nativeElement.click();
                    }, 5000);
  
  
  
              }
  </code></pre>
  
  <p>component 2 app-component2</p>
  
  <pre><code>import { Component, Input, OnInit, Output, EventEmitter ,ElementRef, ViewChild,AfterViewInit } from '@angular/core';
  
  export class Component2 implements OnInit,AfterContentInit {
      @ViewChild('formkeyRefId',{static: false}) formkeyRefId: ElementRef;
  
      constructor(public myElement: ElementRef){}
        this.afterViewInitExecuted = false; 
       ngAfterContentInit() {
        this.afterViewInitExecuted = true; 
     }
  
      formEventEmitter(event) {
  
          if (event &amp;&amp; this.afterViewInitExecuted) {
             setTimeout(() =&gt; {
                console.log(this.formkeyRefId.nativeElement);
              }, 5000);
  
               //this.formkeyRefId.nativeElement.click();
              //const  el: HTMLElement = this.myDiv.nativeElement;
              //e1.click();
          }
  
          reloadContent() {
               getdata();
          }
  
  
  
  }
  </code></pre>
  
  <p>tried to test whether id exist in another component</p>
  
  <pre><code>ngAfterViewInit() {
   this.afterViewInitExecuted = true; 
   console.log(this.formkeyRefId);  Output Undefined
  }
  </code></pre>
  
  <ul>
  <li><p>I Need to Trigger click function <code>reloadContent</code> in component 1 .</p></li>
  <li><p>How to Access Id form another component using #formkeyRefId</p></li>
  <li><p>I can access elementref in same component but not in another component.</p></li>
  <li><p>any suggestion is most welcome.</p></li>
  </ul>