javascript - 查询指令内的 View 变量不起作用

标签 javascript angular typescript angular2-directives

我有一个指令:

@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 试图找到 wrapperlist 在错误的地方。

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

最佳答案

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

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

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

Plunker Example

关于javascript - 查询指令内的 View 变量不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39544912/

相关文章:

angular - 空注入(inject)器错误 : No provider for InjectionToken DocumentToken

javascript - 我如何使这个 angular2 服务稍微同步?

javascript - 带计时器的用户 session 超时

typescript 继承扩展属性

javascript - 构建并运行后,是否可以在浏览器中查看以 Angular 声明的 secret 变量?

返回错误维度的 Javascript 多维数组

javascript - 相对于元素当前颜色(色调、饱和度、亮度)的 jQuery 颜色动画

javascript - Navbar 更多在右侧

javascript - 使用 angularjs 想要存储已检查的 Assets

typescript - 将 `ConstructorParameters<T>` 元组映射到对象类型