在Angular2组件中,我使用EventEmitter发出带参数的事件。在父组件侦听器中,此参数未定义。这是一个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;
}
}
}
如何将挑选的产品传递给父组件?
答案 0 :(得分:30)
你应该这样的$事件:
<product-picker (pick)="onPick($event)"></product-picker>
它对应于告诉关联的EventEmitter的emit方法时提供的值。
在您的情况下,作为参数提供的item变量对应于什么。