首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我可以使用EventEmitter从angular2组件传递变量吗?

我可以使用EventEmitter从angular2组件传递变量吗?
EN

Stack Overflow用户
提问于 2016-02-05 10:21:50
回答 1查看 9.4K关注 0票数 8

我是angular2的新手,所以如果我用了错误的术语来描述我的问题,请原谅。

我有一个简单的组件,让用户选择一个选项。现在,我想将此选项分配给父组件。我是这样做的:

代码语言:javascript
运行
复制
// 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);
   }
}

在主要组件中,我将它包含在模板中,如下所示:

代码语言:javascript
运行
复制
<my-selector-component (selectEvent)="onItemSelected(selectedItemId)"></my-selector-component>

函数确实会得到调用,但是变量是未定义的:

代码语言:javascript
运行
复制
onItemSelected(selectedItemId: string){
    console.log("onItemSelected(" + selectedItemId + ")");
}

控制台输出是:

日志:onItemSelected(未定义)

那么,我缺少什么呢?,事件被发送,函数被调用,但是参数丢失了,

也许其他形式的绑定到所选的Id会更好。只要父组件能够对视图组件中的新选择做出反应,我对任何类型的解决方案都是开放的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-05 10:23:04

您需要使用$event变量来获取触发事件时发送的值:

代码语言:javascript
运行
复制
<my-selector-component (selectEvent)="onItemSelected($event)">
</my-selector-component>

作为EventEmitterEventEmitter方法的参数提供的值对应于它。

票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35221646

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档