简体   繁体   中英

Angular2 - ViewChild from a 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 this is the corrent syntax..

My html is

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

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM