Angular2 - ViewChild from a Directive
我有一个名为EasyBoxComponent的组件,
和带有此viewchild
的指令
1 | @ViewChild(EasyBoxComponent) myComponent: EasyBoxComponent; |
this.myComponent始终未定义
我以为这是科伦特语法。.
我的html是
1 2 | <my-easybox></my-easybox> <p myEasyBox data-href="URL">My Directive</p> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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与AfterContentInit接口一起使用,因此模板应类似于:
1 2 3 | <p myEasyBox data-href="URL"> <my-easybox></my-easybox> </p> |
和指令:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | @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 2 | <my-easybox #myBox></my-easybox> <p [myEasyBox]="myBox" data-href="URL">My Directive</p> |
-
1 | @Input('myEasyBox') myComponent: EasyBoxComponent; |