Call child component methods from parent


#1

Hello everybody,
I want to call the child component methods, like we can do it for properties using @Input(), but I don’t know how I can do it.
Please help.
Thank you in advance :smiley:


#2

What you need is to bind to the event in the component, the only way i know off as today is:

Pass an event emitter from parent to child, subscribe to it and in callback call the child method you want to bind as well as the parameters from the event emitter.

Hope you get a better answer.


#3

Thank you luchillo17,
I am beginner on ionic 2, so please if you have any example give it to me


#4

Just search for the angular 2 event emitter service in docs, it has some examples, import it and pass it as an input on the child element, in child constructor subscribe to it as i told you and in parent when you need to call the child method just emit the event in the eventEmitter or something, i had used it before but i have changed it to use observables, which would also work for you but are a bit more complicated and you might not need that much.

[Edit]: After seeing the docs i notice it’s not very clear: https://angular.io/docs/ts/latest/api/core/index/EventEmitter-class.html
However instructions i give are very explicit, if you don’t know how to import, declare a var in parent, declare an input in child, subscribe in child an copy the emit part of the docs in parent when needing to call child method, maybe you need to study a bit more about Rxjs.


#5

Good frameworks subtly push you into adopting good design practices. Any time I find myself struggling with something that the framework doesn’t really seem to want to make easy to do, I find a much more productive question to ask myself than “how do I do this thing?” is “what am I really trying to achieve, and is there a way to do that that fits nicely within the framework?”.

“How do I call methods of one view from another?” and its cousin “how do I get a reference to one view from another?” are some of the most common themes I see on these forums. I firmly believe that almost every single time (yes, there are rare exceptions like interfacing with non-Angular library code), there is a much better way to achieve the ultimate goal.


#6

Thank you all, I found a solution, I used @ViewChild(CompTest) child:CompTest; in the parent page, then when I need to call a method I use this.child.myMethod() .


Call nav root's function from ion-menu
#7

Hi @Nanosoft i use this method but i get Cannot read property ‘myMethod’ of undefined error…how to fix it?