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);
}
}
,你定义者'myComponent'? –
指令没有视图,因此'@ViewChild()'没有意义。改为使用'@ContentChild()'。如果它不起作用,请提供更多的代码来演示您试图完成的任务。 –
您不能使用ContentChild()或者@ViewChild()来查询组件外部的内容。只有投影内容(如MyDirective文本)或组件视图中的直接子项。 ''是具有指令的元素的兄弟。 Angular没有提供查询它的方法。你可以使用'querySelector',但可能有更好的方法。但是我需要了解你想要解决的实际问题,以便能够提出建议。 –