Michalis
Michalis

Reputation: 6926

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);
  }
}

Upvotes: 18

Views: 27867

Answers (2)

forivall
forivall

Reputation: 9891

Since the component is not the child of the directive, the child selector will not work.

Instead, use references:

<my-easybox #myBox></my-easybox>
<p [myEasyBox]="myBox" data-href="URL">My Directive</p>
@Input('myEasyBox') myComponent: EasyBoxComponent;

Upvotes: 1

Julia Passynkova
Julia Passynkova

Reputation: 17859

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);
  }
}

Upvotes: 17

Related Questions