我有一个组件,ChildComponent和GrandChildComponent。我希望组件侦听组件的GrandChildComponent在ngViewAfterInit中发出的事件。但是,当我试图通过@ViewChild访问GrandChildComponent时,组件无法访问我的GrandChildComponent。这是不可能的,还是有任何其他方式来实现这一点?
发布于 2019-04-05 13:06:20
您真正需要的是组件间的交互。
一种方法是按照你的建议,让孙女以某种方式得到这个活动,但这会很麻烦。那么,如果出于设计原因,您希望更改通信组件之间的关系呢?
惯用的方法是让组件共享信息,不管它们在模板中的关系如何。
角文档在这一页的这一部分中很好地描述了这一点(查看整个页面,以便更好地理解我刚才解释的内容)。
发布于 2021-09-16 21:08:40
因为你可以调用一个孩子的函数,你可以让孩子调用孙子的函数。不知道这是不是最好的主意,但这是可能的。
父母:
@ViewChild(ChildComponent) child!: ChildComponent;
makeGrandchildDoSomething() {
this.child.callChild();
}儿童:
@ViewChild(GrandchildComponent) grandchild!: GrandchildComponent;
callChild() {
this.grandchild.doSomething();
}孙女:
doSomething() {
//grandchild special function
}备注:
@ViewChild,孩子必须在视图中。@ViewChild(ChildComponent, { static: false })@Output提高返回值。https://stackoverflow.com/questions/55535705
复制相似问题