Angular2 访问组件内的选择事件更改 [英] Angular2 access a select event change within the component
问题描述
使用 Angular2s 表单并尝试找出使用选择处理事件的过程.我有一个存储在选项中的对象 Heros.我想要做的是,当我英雄被选中时,触发一个事件到父组件,该事件将对结果做一些事情.但是,我找不到在选择更改时能够接收事件的具体示例(即列表中的新英雄被选中).
Working with Angular2s forms and trying to figure out the process of handling events with selects. I have an object Heros that is stored in the options. What I want to do is that when I hero is selected, trigger an event to the parent component that will do something with the results. However, I can't find a concrete example of being able to receive an event when the selection has changed (ie a new hero in the list as been selected).
interface Hero {
id: number;
name: string;
}
@Component({
selector: 'my-app',
template:`
<h1>{{title}}</h1>
<form>
<select>
<option *ngFor="#hero of heros "
[value]="hero">
{{hero .name}}
</option>
</select>
</form>
`
})
export class AppComponent {
@Input() heros:Observable<Hero>
@Output("selectedHeroChange") selectedHeroChange:EventEmitter<any> = new EventEmitter
onHeroChange(hero:Hero){
this.selectedHeroChange._next(hero);
}
}
提前致谢!
推荐答案
在选择更改时执行代码并使用 id
属性或 index
作为值`:
Execute code on select change and use an id
property or index
as value`:
<select (change)="onHeroChange($event)">
<option *ngFor="#hero of heros; #i=index"
[value]="hero.id">
<!-- [value]="i" -->
{{hero.name}}
</option>
</select>
从事件中获取选定的值
onHeroChange(event:Event):void {
Hero hero = heros.firstWhere(
(Hero hero) => hero.id == (event.target as SelectElement).value);
// Hero hero = heros[int.parse((event.target as SelectElement).value)];
selectedHero = hero;
selectedHeroChange.add(hero);
}
另见https://github.com/angular/angular/issues/4843#issuecomment-170147058
这篇关于Angular2 访问组件内的选择事件更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!