Can I pass variables using EventEmitter from angular2 component?

I am new to angular2, so please excuse me if I use the wrong terms when describing my problem.

I have a simple component that allows the user to select a parameter. Now I want to send this option to the parent component. I'm doing it:

// 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 as follows:

 <my-selector-component (selectEvent)="onItemSelected(selectedItemId)"></my-selector-component> 

And the function receives calls, but the variable is undefined:

 onItemSelected(selectedItemId: string){ console.log("onItemSelected(" + selectedItemId + ")"); } 

console output:

log: onItemSelected (undefined)

So what am I missing? An event is dispatched and the function is called, but the parameter is lost .

Perhaps some other form of binding to the selected identifier would be best. I am open to any solution as long as the parent component can respond to a new selection from the view component.

+6
source share
1 answer

You need to use the $event variable to get the value you sent when the event fires:

 <my-selector-component (selectEvent)="onItemSelected($event)"> </my-selector-component> 

The value that you provide as the parameter of the emit method for EventEmitter matches it.

+11
source

All Articles