I am new to angular2 so please excuse if I use the wrong terms in describing my problem.
I have a simple component that lets a user choose an option. Now I want to dispatch this option to the parent component. I am doing this:
// import the necessary angular2 resources:
import {Component, Output, EventEmitter} from 'angular2/core';
...
// create the emitter in my component class:
export class MyClassThatLetsUserSelectSomeContentId{
@Output() selectEvent: EventEmitter<any> = new EventEmitter();
public selectedId: string;
// this does get called, showing the correct id in the console
onSelect(selectedItem: MyCustomItem){
this.selectedId = selectedItem.id;
console.log("selectedId:" + this.selectedId);
this.selectEvent.emit(this.selectedId);
}
}
and in the main component I include it in the template like this:
<my-selector-component (selectEvent)="onItemSelected(selectedItemId)"></my-selector-component>
And the function does get calles, but the variable is undefined:
onItemSelected(selectedItemId: string){
console.log("onItemSelected(" + selectedItemId + ")");
}
the console output is:
log: onItemSelected(undefined)
So what am I missing? The event is sent and the function gets called but the parameter is lost.
Maybe some other form of binding to the selected Id would be better altogether. I am open to any kind of solution as long as the parent component can react to a new select from the view component.
EventEmitter allows us to emit any type of object, so we will take advantage of it. For passing the parameters, we will wrap all the parameters inside the curly brackets (this will combine them as a single object) and pass it to the emit method.
The problem here is that an EventEmitter function can't return a value since it's asynchronous (although from rc2 it seems that this is optional by passing true to the new EventEmitter function? Even doing so won't fix this issue however). So isValid will always be true regardless of what the function returns.
So to emit an event from the child component class to the parent component class, use EventEmitter with @Output() decorator.
You need to use the $event
variable to get the value you send when triggering the event:
<my-selector-component (selectEvent)="onItemSelected($event)">
</my-selector-component>
The value you provide as parameter of the emit
method of the EventEmitter
corresponds to it.
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