Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass variables using EventEmitter from angular2 component?

Tags:

angular

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.

like image 723
Björn Kechel Avatar asked Feb 05 '16 10:02

Björn Kechel


People also ask

How do you pass parameters in event emitter?

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.

Can EventEmitter return value?

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.

Which decorator can be used by child component to expose an EventEmitter property when something happens?

So to emit an event from the child component class to the parent component class, use EventEmitter with @Output() decorator.


1 Answers

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.

like image 57
Thierry Templier Avatar answered Oct 04 '22 19:10

Thierry Templier