调用子组件的方法 [英] Call a method of the child component

查看:59
本文介绍了调用子组件的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的嵌套子组件:

I have a nested child component like this:

<app-main>
    <child-component />
</app-main>

我的appMain组件需要在子组件上调用方法.

My appMain component needs to invoke a method on child-component.

如何在子组件上调用方法?

How to invoke a method on the child-component?

推荐答案

您可以使用

@ViewChild('childComponent') child;

其中childComponent是模板变量>`或

where childComponent is a template variable <some-elem #childComponent>` or

@ViewChild(ComponentType) child;

其中ComponentType是组件或指令的类型,然后在ngAfterViewInit中或事件处理程序中调用child.someFunc().

where ComponentType is the type of a component or directive and then in ngAfterViewInit or an event handlers call child.someFunc().

ngAfterViewInit() {
  console.log(this.child);
}

另请参见获取模板中的元素

这篇关于调用子组件的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆