[英]Angular2 - ViewChild from a Directive
我有一个名为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); } }
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);
}
}
由于组件不是指令的子组件,因此子选择器将不起作用。
相反,使用引用
<my-easybox #myBox></my-easybox>
<p [myEasyBox]="myBox" data-href="URL">My Directive</p>
-
@Input('myEasyBox') myComponent: EasyBoxComponent;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.