Angular2 - ViewChild from a Directive

Michalis picture Michalis · Apr 7, 2017 · Viewed 13.6k times · Source

I have a component with this name EasyBoxComponent, and a directive with this viewchild

@ViewChild(EasyBoxComponent) myComponent: EasyBoxComponent;

this.myComponent is always undefined

I thought this is the corrent syntax..

My html is

<my-easybox></my-easybox>
<p myEasyBox data-href="URL">My Directive</p>

Answer

Julia Passynkova picture Julia Passynkova · Apr 15, 2017

ContentChild works with AfterContentInit interface, so the template should be like:

<p myEasyBox data-href="URL">
    <my-easybox></my-easybox>
</p>

and directive:

@Directive({
  selector: '[myEasyBox]'
})
export class EasyBoxDirective implements AfterContentInit {
  @ContentChild(EasyBoxComponent) myComponent: EasyBoxComponent;
  @ContentChild(EasyBoxComponent) allMyCustomDirectives;

  ngAfterContentInit(): void {
    console.log('ngAfterContentInit');
    console.log(this.myComponent);
  }

  constructor() {
  }

  @HostListener('click', ['$event'])
  onClick(e) {
    console.log(e);
    console.log(e.altKey);
    console.log(this.myComponent);
    console.log(this.allMyCustomDirectives);
  }
}