Angular 2 - How to trigger a method on a child from the parent
I think these might be what you're looking for:
https://angular.io/guide/component-interaction#parent-interacts-with-child-via-local-variable
https://angular.io/guide/component-interaction#parent-calls-an-viewchild
You can access child properties and methods using local variables within the template or using the @ViewChild
decorator in the parent's component class.
@ViewChild
is the right solution, but the documentation linked above was a bit unclear for me, so I pass a bit more friendly explanation which helped me to understand it.
Let's have a ChildComponent
with a method:
whoAmI() {
return 'I am a child!!';
}
And the parent component, where we can call method above by using '@ViewChild` technique:
import { Component, ViewChild, OnInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
@ViewChild(ChildComponent) child: ChildComponent;
ngOnInit() {
console.log(this.child.whoAmI()); // I am a child!
}
}