【问题标题】:Query for view variables inside directive not working查询指令内的视图变量不起作用
【发布时间】: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 试图在错误的位置找到wrapperlist

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

【问题讨论】:

  • 您是否将其包含在您模块的declarations 中?您在控制台中收到了哪些(如果有)消息?

标签: javascript angular typescript angular2-directives


【解决方案1】:

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

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

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

Plunker Example

【讨论】:

  • @GünterZöchbauer 我也没有,但显然他们有。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-05
  • 2016-11-16
  • 2014-05-16
  • 2016-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多