Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - ViewChild from a Directive

I have a component with the name EasyBoxComponent, and a @Directive with this @Viewchild:

@ViewChild(EasyBoxComponent) myComponent: EasyBoxComponent;

I thought this was the correct syntax, but this.myComponent is always undefined.


Here's the whole code:

<my-easybox></my-easybox>
<p myEasyBox data-href="URL">My Directive</p>
import { Directive, AfterViewInit, HostListener, ContentChild } from '@angular/core';
import { EasyBoxComponent } from '../_components/easybox.component';

@Directive({
  selector: '[myEasyBox]'
})
export class EasyBoxDirective implements AfterViewInit {

  @ContentChild(EasyBoxComponent) myComponent: EasyBoxComponent;
  @ContentChild(EasyBoxComponent) allMyCustomDirectives;

  constructor() {
  }

  ngAfterViewInit() {
    console.log('ViewChild');
    console.log(this.myComponent);
  }

  @HostListener('click', ['$event'])
  onClick(e) {
    console.log(e);
    console.log(e.altKey);
    console.log(this.myComponent);
    console.log(this.allMyCustomDirectives);
  }
}
like image 962
Michalis Avatar asked Apr 07 '17 06:04

Michalis


1 Answers

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

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

and the @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);
  }
}
like image 129
Julia Passynkova Avatar answered Nov 07 '22 00:11

Julia Passynkova