Angular pass data from child to parent

nikagar4 picture nikagar4 · Dec 17, 2016 · Viewed 16k times · Source

I'm learning/working on Angular project, I've done a lot and I try to do the things "right way", so now what i want to do is this:

I want to get the variable (output) from child component to parent component, but I don't want to use output, I don't want to listen to it, I want to get it whenever parent needs it, something like child.getVariable() I've came across one post which said I should use childview but the question wasn't same as mine, so I want to know is it a good practice to use childview to get data from child component or not?

Answer

jezzah picture jezzah · Dec 17, 2016

Do you only need access to the child component's variable from within the parent's template? If so, you can use:

<child-component #childComponentRef></child-component>

You then have access to #childComponentRef.someVariable from within your parent template. Otherwise I think the Angular team recommends shared services. They are a bit more versatile anyways. See https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-and-children-communicate-via-a-service