I am just playing around with @ViewChild/@ContentChild, and I was surprised to see that the @ViewChild is not working inside directive and is working fine for component.But in Directive its not working. I tried with AfterViewInit hook, so life cycle hook is not the reason. Something else is the issue here,Please find the code below.
app.component.html
<div appMain >
<div #testContentDiv style="background-color: grey">
<p>This is the first p tag</p>
<p>This is the second p tag</p>
</div>
<div #testViewDiv style="background-color: yellow">
<p>This is the first p tag</p>
<p>This is the second p tag</p>
</div>
<app-test-child></app-test-child>
</div>
test-dir.ts --Directive
import { Directive, ViewChild, ElementRef, OnInit, AfterViewInit, AfterContentInit, ContentChild } from '@angular/core';
@Directive({
selector: '[appMain]'
})
export class MainDirective implements OnInit, AfterContentInit, AfterViewInit {
constructor() { }
// tslint:disable-next-line:member-ordering
@ContentChild('testContentDiv') testContent: ElementRef;
@ViewChild('testViewDiv') testView: ElementRef;
ngOnInit() {
//Called after the constructor, initializing input properties, and the first call to ngOnChanges.
//Add 'implements OnInit' to the class.
// console.log(this.test.nativeElement);
}
ngAfterContentInit() {
//Called after ngOnInit when the component's or directive's content has been initialized.
//Add 'implements AfterContentInit' to the class.
console.log('Content Div: ngAfterContentInit: ' + this.testContent.nativeElement);
// console.log('View Div: ngAfterContentInit: ' + this.testView.nativeElement);
}
ngAfterViewInit() {
//Called after ngAfterContentInit when the component's view has been initialized. Applies to components only.
//Add 'implements AfterViewInit' to the class.
console.log('Content Div:ngAfterViewInit: ' + this.testContent.nativeElement);
console.log('View Div: ngAfterViewInit: ' + this.testView.nativeElement);
}
}
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = "App works";
constructor() {
}
}
@ContentChild
should work – Agave