子组件上Execute方法 [英] Execute method on child component

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

问题描述

我有一个父组件和子组件。我希望能够从父组件的某些方法调用子组件上一些孩子的方法。
有没有办法让父类和呼叫孩子的公共方法引用到子组件实例?

I have a parent component and a child component. I want to be able to call some child method on the child component from some method on the parent component. Is there a way to get a reference to the child component instance on the parent's class and call child's public methods?

@Component({
    selector: 'child-component'
})
@View({
    template: `<div>child</div>`
})
class ChildComponent{
    constructor () {

    }

    doChildEvent () {
        //  some child event
    }
}

@Component({
    selector: 'parent-component'
})
@View({
    template: `
        <child-component #child></child-component>
    `,
    directives: [
        ChildComponent
    ]
})
class ParentComponent {
    private child:ChildComponent;

    constructor () {

    }

    onSomeParentEvent() {
        this.child.doChildEvent();
    }
}

我试图把对孩子的哈希模板,并在课堂上,但没有成功引用它。

I tried putting a hash on the child in template and referencing it in the class but no success.

推荐答案

这是什么样的 ViewChild 是:

This is what ViewChild is for:

//don't forget to import ViewChild

class ParentComponent {
    @ViewChild(ChildComponent) private child:ChildComponent;

    constructor () {
       //this.child is undefined because constructor is called before AfterViewInit
    }

    onSomeParentEvent() {
        //this.child contains the reference you're looking for 
        this.child.doChildEvent();
    }
}

假设 onSomeParentEvent 之后触发的 AfterViewInit
this.child 将包含子组件的引用。

Assuming onSomeParentEvent is fired after AfterViewInit, this.child will contain a reference to the child component.

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

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