我有一个指令:
@Directive({
selector: '[myDirective]'
})
export class MyDirective implements AfterViewInit {
@ViewChild('wrapper') wrapper;
@ViewChild('list') list;
ngAfterViewInit() {
// Both of these are undefined
console.log(wrapper, list);
}
}
它需要在它正在使用的 View 中查询变量。
假设我的组件之一 MyComponent
中有这个模板:
<div #wrapper myDirective>
<ul #list></ul>
</div>
它需要找到这些变量,但指令从来没有按照我现在的方式做到这一点。我猜测为什么会这样,因为指令实际上没有 View ,ngAfterViewInit
运行得太快和/或 @ViewChild
试图找到 wrapper
和 list
在错误的地方。
如何确保指令可以找到变量?
最佳答案
只需将 ViewChild
更改为 ContentChild
。我想它应该可以工作
export class MyDirective implements AfterViewInit {
@ContentChild('wrapper') wrapper;
@ContentChild('list') list;
ngAfterContentInit() {
console.log(this.wrapper, this.list);
}
}
关于javascript - 查询指令内的 View 变量不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39544912/