title: In Angular (Angular 4) ,Not able to access the ElementRef of another Component using @ViewChild
body: <p>I was trying to access the child component using @ViewChild 
  in Parent Component(AppComponent.ts)</p>
  
  <pre><code>      import { Component, ViewChild, ElementRef, AfterViewInit} from '@angular/core';
        import { HeaderComponent } from '../app/components/header/header.component';
        @Component({
          selector: 'app-root',
          templateUrl: './app.component.html',
          styleUrls: ['./app.component.less']
        })
        export class AppComponent implements AfterViewInit {
          title = 'app';
          @ViewChild('myHeader') myHeader: ElementRef;
          ngAfterViewInit() {
            this.myHeader.nativeElement.style.backgroundColor = 'red';
          }  
        }
  </code></pre>
  
  <p>Parent HTML(app.component.html)</p>
  
  <pre><code>&lt;div&gt;
      &lt;app-header&gt;&lt;/app-header&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>Now Child HeaderComponent is as below:</p>
  
  <pre><code>    import { Component, OnInit, ViewEncapsulation } from '@angular/core';
  
      @Component({
        selector: 'app-header',
        templateUrl: './header.component.html',
        styleUrls: ['./header.component.less']
      })
      export class HeaderComponent implements OnInit {
        constructor() {
        }
        ngOnInit() {
  
        }
  
      }
  </code></pre>
  
  <p>Header HTML(header.component.html)(Child)</p>
  
  <pre><code>&lt;div #myHeader&gt; hello&lt;/div&gt;
  </code></pre>
  
  <p>In ngAfterViewInit function  this.myHeader.nativeElement is giving error.</p>
  
  <pre><code>AppComponent_Host.html:1 ERROR TypeError: Cannot read property 'nativeElement' of undefined
  at AppComponent.webpackJsonp.../../../../../src/app/app.component.ts.AppComponent.ngAfterViewInit (app.component.ts:12)
  at callProviderLifecycles (core.es5.js:11189)
  at callElementProvidersLifecycles (core.es5.js:11164)
  at callLifecycleHooksChildrenFirst (core.es5.js:11148)
  at checkAndUpdateView ....
  </code></pre>
  
  <p>Although when i tried to access any child defined in Parent HTML(app.component.html)  its working like below:</p>
  
  <pre><code>&lt;div #myHeader&gt; &lt;app-header&gt;&lt;/app-header&gt;&lt;/div&gt;
  </code></pre>
  
  <p>But i want to access any ElementRef in header.component.html.I tired to have View Encapsulation also like below.</p>
  
  <pre><code>encapsulation: ViewEncapsulation.None,
  </code></pre>
  
  <p>in HeaderComponent but it also not working.Please let me know what else i am missing here. </p>