Angular2 - ViewChild from the directive

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 it was corrent syntax.

My html

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

}
Run codeHide result
+4
source share
2 answers

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

<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);
  }
}
+5
source

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

Use links instead

<my-easybox #myBox></my-easybox>
<p [myEasyBox]="myBox" data-href="URL">My Directive</p>

-

@Input('myEasyBox') myComponent: EasyBoxComponent;
-1
source

Source: https://habr.com/ru/post/1674279/


All Articles