选定下拉列表中的Angular 2 @Input参数

时间:2016-10-18 09:02:16

标签: angular input

我遇到从父组件传递@input参数的问题。我正在尝试创建一个级联下拉列表。我在父组件中有一个下拉列表,在子组件中有一个。在选择父下拉列表时,我想填充子下拉列表。我正在尝试使用@Input参数来实现它,但它似乎没有用。

[http://plnkr.co/edit/uyE5XIasBdh3OwQhvHwb?p=preview]

export class Hero {
  constructor(public id:number, public name:string)  
}

App Component 

import { Hero } from './hero';

const HEROES: Hero[] = [
  { id: 11, name: 'Mr. Nice' },
  { id: 12, name: 'Narco' },
  { id: 13, name: 'Bombasto' },
  { id: 14, name: 'Celeritas' }
];

@Component({
  selector: 'my-app',
  template: `
    <h1>{{title}}</h1>
    <h2>My Heroes</h2>
     <select class="form-control" (change)="onSelect($event.target.value)">
        <option *ngFor="let hero of heroes" value="{{hero.id}}">{{hero.name}}</option>
    </select>
    <my-hero-detail [hero]="selectedHero"></my-hero-detail>
  `
})
export class AppComponent {
  heroes = HEROES;
  selectedHero: Hero;

  onSelect(hero: string): void {
    this.selectedHero = new Hero(hero,hero);
  }
}


Child Component

@Component({
  selector: 'my-hero-detail',
  template:`
    <div *ngIf="hero">
      <div>details!</div>
      <h2>Name: {{hero.name}}</h2>
      <div><label>id: </label>{{hero.id}}</div>

    </div>`
})
export class HeroDetailComponent {
  @Input()
  hero: Hero;
}

1 个答案:

答案 0 :(得分:0)

使用[ngValue]将对象用作<option>的值。这种方式[(ngModel)]="selectedHero"将此类对象分配给selectedHero

Plunker example