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?
You can get a reference to an element using
@ViewChild('childComponent') child;
where childComponent is a template variable <some-elem #childComponent>` or
@ViewChild(ComponentType) child;
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);
}
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);
#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.
Being a son component
@Component({
// configuration
template: `{{data}}`,
// more configuration
})
export class Son {
data: number = 3;
constructor() { }
updateData(data:number) {
this.data = data;
}
}
Having a father component
@Component({
// configuration
})
export class Parent {
@ViewChild(Son) mySon: Son;
incrementSonBy5() {
this.mySon.updateData(this.mySon.data + 5);
}
}
In the father's template
<son></son>
<button (click)="incrementSonBy5()">Increment son by 5</button>
This solution only works for one <son></son>instance in the parent template. If you have more than one instance only will work in the first one of the template.