Per Hornshøj-Schierbeck Per Hornshøj-Schierbeck - 6 months ago 11
Javascript Question

Call a method of the child component

I have a nested child component like this:



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


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

How to invoke a method on the child-component?

Answer

Parent and child can communicate via data binding.

Example:

@Component({
    selector: 'child-component',
    inputs: ['bar'],
    template: `"{{ bar }}" in child, counter  {{ n }}`
})
class ChildComponent{
    constructor () {
        this.n = 0;
    }
    inc () {
        this.n++;
    }
}

@Component({
    selector: 'my-app',
    template: `
        <child-component #f [bar]="bar"></child-component><br>
        <button (click)="f.inc()">call child func</button>
        <button (click)="bar = 'different'">change parent var</button>
    `,
    directives: [ChildComponent]
})
class AppComponent {
    constructor () {
        this.bar = 'parent var';
    }
}

bootstrap(AppComponent);  

Demo

#f creates a reference to the child component and can be used in template or passed to function. Data from parent can be passed by [ ] binding.