【问题标题】:Angular 2 @Input parameter from selected dropdown来自选定下拉列表的 Angular 2 @Input 参数
【发布时间】:2016-10-18 09:02:15
【问题描述】:

我在从父组件传递 @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;
}

【问题讨论】:

  • 请直接在问题中添加相关代码。 SO不允许Plunker链接而不直接添加代码是有原因的。
  • 我在上面的 plunker 代码中看不到子组件的下拉菜单。您从父母传递给孩子的唯一输入是 "hero" ,这是一个
  • 对不起,这是我第一次发帖,所以我不知道。 @GopinathShiva 下拉菜单在 app.components.ts 模板中。
  • 这没有帮助。请编辑您的问题并在此处添加代码。 cmets 中的代码不可读,谢谢。
  • @GünterZöchbauer 有帮助吗?

标签: angular input


【解决方案1】:

使用[ngValue] 将对象用作&lt;option&gt; 的值。这样[(ngModel)]="selectedHero"将这样一个对象分配给selectedHero

Plunker example

【讨论】:

  • 非常感谢。三天以来我一直在拉头发。
猜你喜欢
  • 2016-10-24
  • 1970-01-01
  • 1970-01-01
  • 2012-11-17
  • 2020-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多