首页 > 解决方案 > 我们可以/如何通过 @ViewChild 以角度访问孙子组件吗

问题描述

我有一个组件、ChildComponent 和一个 GrandChildComponent。我希望组件在组件的 ngViewAfterInit 中侦听 GrandChildComponent 发出的事件。但是当我尝试通过@ViewChild 访问 GrandChildComponent 时,无法从 Component 访问我的 GrandChildComponent。这是不可能的还是有其他方法可以实现这一点?

标签: angular

解决方案


由于您可以调用子函数,因此您可以让子函数调用孙函数。不确定这是否是最好的主意,但这是可能的。

家长:

@ViewChild(ChildComponent) child!: ChildComponent;

makeGrandchildDoSomething() {
    this.child.callChild();
}

孩子:

@ViewChild(GrandchildComponent) grandchild!: GrandchildComponent;

callChild() {
    this.grandchild.doSomething();
}

孙子:

doSomething() {
    //grandchild special function
}

笔记:

  • @ViewChild像这样使用,孩子必须在视图中。
  • Angular 8+ 可能需要:@ViewChild(ChildComponent, { static: false })
  • 同样,您可以使用冒泡返回值@Output

推荐阅读