Angular2 - 来自指令的ViewChild

时间:2017-04-07 06:44:46

标签: angular angular2-directives

我有一个名为EasyBoxComponent的组件, 和这个viewchild的指令

@ViewChild(EasyBoxComponent) myComponent: EasyBoxComponent;

this.myComponent始终未定义

我认为这是正确的语法..

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

}

2 个答案:

答案 0 :(得分:9)

ContentChild与AfterContentInit接口一起使用,因此模板应该是:

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

和指令:

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

答案 1 :(得分:0)

由于组件不是指令的子组件,因此子选择器将不起作用。

相反,请使用参考

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

-

@Input('myEasyBox') myComponent: EasyBoxComponent;