angular - 我们可以/如何通过 @ViewChild 以角度访问孙子组件吗
问题描述
我有一个组件、ChildComponent 和一个 GrandChildComponent。我希望组件在组件的 ngViewAfterInit 中侦听 GrandChildComponent 发出的事件。但是当我尝试通过@ViewChild 访问 GrandChildComponent 时,无法从 Component 访问我的 GrandChildComponent。这是不可能的还是有其他方法可以实现这一点?
解决方案
由于您可以调用子函数,因此您可以让子函数调用孙函数。不确定这是否是最好的主意,但这是可能的。
家长:
@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
推荐阅读
- python - 如何阻止散景在 Jupyter Notebook 中打开新标签?
- ubuntu - 如何在 Ubuntu 的 Visual Studio Code 中将多行代码转换为单行代码
- linux - Makefile PHONY 在大文件中的使用
- java - 如何使用 JPA 锁定数据库行,直到另一个表被更新
- asp.net - 默认页面是如何在我的 asp.net 项目中首先执行的
- reactjs - 如何在 Linux 上以后台模式启动 React JS 应用程序?
- python - 如何在速度方面提高我的“for”循环性能?
- javascript - 使用 boost.asio 向 REST API 服务器发送 POST 请求时出错
- sql - 总结sql中的相邻列
- python -
使用python在XML中组合文本时如何传递元素?