Sagi
Sagi

Reputation: 1612

Execute method on child component

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.

Upvotes: 1

Views: 916

Answers (1)

drew moore
drew moore

Reputation: 32680

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();
    }
}

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

Upvotes: 6

Related Questions