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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With