【发布时间】:2016-09-17 08:59:20
【问题描述】:
我有一个指令:
@Directive({
selector: '[myDirective]'
})
export class MyDirective implements AfterViewInit {
@ViewChild('wrapper') wrapper;
@ViewChild('list') list;
ngAfterViewInit() {
// Both of these are undefined
console.log(wrapper, list);
}
}
需要在使用它的视图中查询变量。
假设我的一个组件中有这个模板,MyComponent:
<div #wrapper myDirective>
<ul #list></ul>
</div>
它需要找到这些变量,但该指令从来没有像我现在拥有的那样设法做到这一点。我对为什么会发生这种情况的猜测是,由于指令实际上没有视图,ngAfterViewInit 运行得太快和/或@ViewChild 试图在错误的位置找到wrapper 和list。
如何确保指令可以找到变量?
【问题讨论】:
-
您是否将其包含在您模块的
declarations中?您在控制台中收到了哪些(如果有)消息?
标签: javascript angular typescript angular2-directives