I was trying to access the child component using @ViewChild in Parent Component(AppComponent.ts)
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';
}
}
Parent HTML(app.component.html)
<div>
<app-header></app-header>
</div>
Now Child HeaderComponent is as below:
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() {
}
}
Header HTML(header.component.html)(Child)
<div #myHeader> hello</div>
In ngAfterViewInit function this.myHeader.nativeElement is giving error.
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 ....
Although when i tried to access any child defined in Parent HTML(app.component.html) its working like below:
<div #myHeader> <app-header></app-header></div>
But i want to access any ElementRef in header.component.html.I tired to have View Encapsulation also like below.
encapsulation: ViewEncapsulation.None,
in HeaderComponent but it also not working.Please let me know what else i am missing here.