It\'s possible to send data from the parent to a child through @Input, or to call a method on the parent from the child with @Output, but I\'d like to do exactly the other w
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!
}
}