在我的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
中的所有@Output
和Component1
值,但不包含method1()
之类的方法。
我想知道的事情:
我如何访问this.child.method1()
?
我真的不明白你为什么要这么做。通常,有必要从子级调用父方法,例如关闭模式等。但是请查看此链接https://stackoverflow.com/a/38974968/7393630。它可能会帮助您想要做的事情。
我建议不要尝试在父级中调用子级方法。考虑重新考虑应用程序的体系结构和数据流。您可能希望它与此相反,使用事件发射器从子级调用父级中的方法来进行通信https://angular.io/guide/component-interaction#parent-listens-for-child-event。
您是否尝试过在子组件中使用公共方法。