In Angular2 component I use EventEmitter to emit an event with parameter. In the parent component listener this parameter is undefined. Here is a plunker:
import {Component, EventEmitter, Output} from 'angular2/core'
@Component({
template: `<ul>
<li *ngFor="#product of products" (click)="onClick(product)">{{product.name}}</li>
</ul>`,
selector: 'product-picker',
outputs: ['pick']
})
export class ProductPicker {
products: Array<any>;
pick: EventEmitter<any>;
constructor() {
this.products = [
{id: 1, name: 'first product'},
{id: 2, name: 'second product'},
{id: 3, name: 'third product'},
];
this.pick = new EventEmitter();
}
onClick(product) {
this.pick.emit(product);
}
}
@Component({
selector: 'my-app',
providers: [],
template: `
<div>
<h2>Pick a product</h2>
<product-picker (pick)="onPick(item)"></product-picker>
</div>
<div>You picked: {{name}}</div>
`,
directives: [ProductPicker]
})
export class App {
name: string = 'nothing';
onPick(item) {
if (typeof item == 'undefined') {
console.log("item is undefined!");
} else {
this.name = item.name;
}
}
}
How to pass the picked product to parent component?
addListener(event, listener) are pretty much similar. It adds the listener at the end of the listener's array for the specified event. Multiple calls to the same event and listener will add the listener multiple times and correspondingly fire multiple times. Both functions return emitter, so calls can be chained.
EventEmitter is a class that helps us create a publisher-subscriber pattern in NodeJS. With an event emitter, we can simply raise a new event from a different part of an application, and a listener will listen to the raised event and have some action performed for the event.
The on() method requires name of the event to handle and callback function which is called when an event is raised. The emit() function raises the specified event. First parameter is name of the event as a string and then arguments. An event can be emitted with zero or more arguments.
The instance of the EventEmmiter also has a method “emit” that emits an event and causes all the EventEmitter to call all the listeners. The EventEmitter called all of the above functions synchronously.
You should $event like this:
<product-picker (pick)="onPick($event)"></product-picker>
It corresponds to the value you provided when telling the emit method of the associated EventEmitter.
In your case the item variable provided as parameter corresponds to nothing.
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