Angular:检查子组件时,我看不到所有方法,只有@Input和@Output

问题描述 投票:1回答:3

在我的Angular应用中,我有一个名为Component1且带有选择器component-1的组件,它的模板包含其自身的嵌套实例:

<div> <component-1></component-1> </div>

因此parent Component1包含child Component1

我的目标:

Component1包含方法method1()。我想从父组件中调用子组件的method1。类似于this.child.method1()

我尝试过的事情:

在组件中,我得到带有以下代码的child@ViewChild(Component1) child: Component1;。如果执行console.log(this.child),我将得到一个对象,其中包含@Input中的所有@OutputComponent1值,但不包含method1()之类的方法。

我想知道的事情:

我如何访问this.child.method1()

angular angular-components viewchild
3个回答
0
投票

我真的不明白你为什么要这么做。通常,有必要从子级调用父方法,例如关闭模式等。但是请查看此链接https://stackoverflow.com/a/38974968/7393630。它可能会帮助您想要做的事情。


0
投票

我建议不要尝试在父级中调用子级方法。考虑重新考虑应用程序的体系结构和数据流。您可能希望它与此相反,使用事件发射器从子级调用父级中的方法来进行通信https://angular.io/guide/component-interaction#parent-listens-for-child-event


0
投票

您是否尝试过在子组件中使用公共方法。

© www.soinside.com 2019 - 2024. All rights reserved.