2017-04-07 42 views
4

ViewChild我有这个名字EasyBoxComponent, 和指令组件与此viewchildAngular2 - 从指令

@ViewChild(EasyBoxComponent) myComponent: EasyBoxComponent; 

this.myComponent永远是不确定的

我认为这是corrent语法。 。

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

 
}

+0

,你定义者'myComponent'? –

+0

指令没有视图,因此'@ViewChild()'没有意义。改为使用'@ContentChild()'。如果它不起作用,请提供更多的代码来演示您试图完成的任务。 –

+0

您不能使用ContentChild()或者@ViewChild()来查询组件外部的内容。只有投影内容(如MyDirective文本)或组件视图中的直接子项。 ''是具有指令的元素的兄弟。 Angular没有提供查询它的方法。你可以使用'querySelector',但可能有更好的方法。但是我需要了解你想要解决的实际问题,以便能够提出建议。 –

回答

5

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

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

相反,使用引用

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

-

@Input('myEasyBox') myComponent: EasyBoxComponent;