Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular pass data from child to parent

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?

like image 934
nikagar4 Avatar asked Dec 17 '16 16:12

nikagar4


2 Answers

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

like image 59
jezzah Avatar answered Oct 15 '22 06:10

jezzah


Register the EventEmitter in your child component as the @Output:

@Output() onDatePicked: EventEmitter<any> = new EventEmitter<any>();
Emit value on click:

public pickDate(date: any): void {
    this.onDatePicked.emit(date);
}

Listen for the events in your parent component's template:

<div>
    <calendar (onDatePicked)="doSomething($event)"></calendar>
</div>

and in the parent component:

public doSomething(date: any):void {
    console.log('Picked date: ', date);
}

Ref : stackoverflow.com/a/42109866/4697384

like image 31
Amit Avatar answered Oct 15 '22 06:10

Amit