我试图在两个组件之间传递一个带有EventEmitter的变量,我在2个不同的.component文件中有这两段代码(我已经删除了样板代码):
@Component({
selector: 'shopping-list-item',
template: `
<form #f="ngForm">
<div class="input">
<label for="item-name">Name</label>
<input type="text" id="item-name" ngControl="inputname">
</div>
<div class="input">
<label for="item-amt">Amount</label>
<input type="text" id="item-amt" ngControl="inputamount">
</div>
<button class="info" (click)="onEdit()">Edit</button>
</form>
`,
inputs:['item'],
outputs:['editted']
})
export class ShoppingListItemComponent {
item = { name: '', amount: 0 };
editted = new EventEmitter({name: form['inputname'], amount: form['inputamount'] });
onEdit(){
this.editted.emit(this.item);
}
}
@Component({
selector: 'shopping-list',
template: `
<section>
<div class="list">
<ul>
<li *ngFor="#listItem of listItems" (click)="onSelect(listItem)">{{listItem.name}} ({{listItem.amount}})</li>
</ul>
</div>
</section>
<section>
<shopping-list-item [item] (editted)="onEditItem($event)"></shopping-list-item>
</section>
`
})
export class ShoppingListComponent {
onEditItem(item:ListItem){
let myindex = this.listItems.indexOf(item);
this.listItems[myindex].name = +$event.name;
this.listItems[myindex].amount = +$event.amount;
}
}
我收到此错误:
Error during evaluation of "editted". `$event is not defined`
如果我将+$event.name
替换为&#34; test&#34;我没有收到错误。
答案 0 :(得分:2)
你所做的事似乎差错了。为了指导您正确的方向,您可以检查此答案。
EventEmitter通常用于传播来自child to parent
组件的数据。
在您的情况下,shoppinlistitem
会将数据传播到shoppinglist
组件,就像这样,
see this working demo
注意:请忽略不正确的命名惯例以及Gunter建议的正确。
<强> shoppinglist.ts 强>
@Component({
selector: 'my-app',
directives:[shoppinglistitem],
template: `
<h2>shopping-list</h2>
{{item|json}}
<shopping-list-item (editted)="onEditItem($event)"></shopping-list-item>
`
})
export class BodyContent {
name:string='Angular1';
onEditItem(arg){
console.log('onEditedItem started');
console.log(arg);
this.item=arg;
}
}
bootstrap(BodyContent, []);
<强> shoppinglistitem.ts 强>
@Component({
selector: 'shopping-list-item',
template: `
<hr>
<h4>ShoppinglistItem</h4>
<br>
<button class="info" (click)="onEdit()">Edit</button>
<hr>
`
})
export class shoppinglistitem {
item = { name: 'micronyks', amount: '0' };
@Output() editted: EventEmitter = new EventEmitter();
constructor() {
console.log('Constructor called');
}
onEdit()
{
this.editted.emit(this.item);
}
}
答案 1 :(得分:0)
此行无效
new EventEmitter({name: form['inputname'], amount: form['inputamount'] });
EventEmitter
仅支持一个构造函数参数
export class EventEmitter<T> extends Subject<T> {
...
constructor(isAsync: boolean = true)