camcam
camcam

Reputation: 2625

Event emitter's parameter is undefined for listener

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?

Upvotes: 27

Views: 19316

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202138

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.

Upvotes: 47

Related Questions