Reputation: 807
simple problem : I want to pass data from a child to its parent when clicking on a button, but the data is always undefined in the parent. I've looked at : Angular's Documentation and at the multitude of posts already sorting this problem out but i'm still stuck with it so..
The child component (<left-panel>
) have a button with a (click)="handleAddTea()"
event handler. When clicked the button emit()
the event through an EventEmitter
that has the @Output
decorator as required.
And I bind this EventEmitter
to a handler in the parent templete with a $ sign in front of the data as documented : (addTeaEvent)="handleAddTeaEvent($data)"
But when the handleAddTeaEvent
function trigger the data is undefined
Here is the related code in the child component :
@Output()
addTeaEvent: EventEmitter<any> = new EventEmitter<any>();
handleAddTea() {
console.log('Add Tea Clicked sending to parent..');
this.addTeaEvent.emit(this.mainTitle)
}
<button class="btn flex__item--middle btn--large btn--call-to-action" (click)="handleAddTea()">
{{addBtnText}}
</button>
And here is the related code in the parent component :
handleAddTeaEvent(stuff: any) {
console.log('from parent', stuff);
}
<left-panel mainTitle="Add a tea" addBtnText="Add tea" (addTeaEvent)="handleAddTeaEvent($data)"></left-panel>
Why is it undefined ?
Upvotes: 0
Views: 173
Reputation: 8558
You need to use $event
instead of $data
in event listener:
<left-panel mainTitle="Add a tea" addBtnText="Add tea" (addTeaEvent)="handleAddTeaEvent($event)"></left-panel>
For further reading: https://angular.io/guide/user-input
Upvotes: 3