查询指令内的视图变量不起作用

Query for view variables inside directive not working

我有一个指令:

@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 运行得太快 and/or @ViewChild 试图找到 wrapperlist 在错误的地方。

如何确保指令可以找到变量?

只需将 ViewChild 更改为 ContentChild。我想它应该可以工作

export class MyDirective implements AfterViewInit {
  @ContentChild('wrapper') wrapper;
  @ContentChild('list') list;

  ngAfterContentInit() {
    console.log(this.wrapper, this.list);
  }
}

Plunker Example