Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
   }    
}

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

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>

get the selected value from the event

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);
}

See also https://github.com/angular/angular/issues/4843#issuecomment-170147058

See also Binding select element to object in Angular 2


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...