Angular 2 selecting 根据传入参数从 select 列表中选择选项

Angular 2 selecting option from select list based on passed in parameter

嗨,希望有人能告诉我遗漏了什么。

在我的 plunker 演示中,我有一个编辑按钮,单击该按钮现在会提供 2 的静态 ID。 (这模拟了一个 id 参数进入我的真实项目中的这个组件)

我想做的是获取传入的 ID 并在下拉列表中找到用户和 select 他们,然后它会填充我的其他字段,就像目前所做的那样 select 来自 select 列表的用户。

在我的代码中我可以看到我有 id 并且可以找到 matches.I 也可以填充 id 字段的全名,但没有设置 select 列表 selected对全名的价值任何帮助表示赞赏。

Html 当前显示具有两种数据绑定的下拉列表和 id 字段

  <select [(ngModel)]="tradesman">
<option>Select</option>
<option [ngValue]="v" *ngFor='let v of _tradesmen'>{{ v.fullname}}</option>

Plunker demo showing where I am up to

谢谢 安迪

应该是[value]="v"而不是[ngValue]="v"。 从你的 plunker 代码来看,你的 class 没有实现 OnInit

根据我所理解的问题,您有一个 ID,您必须根据此 ID 在 select 框中选择值。我希望它在 page load 上,这就是我使用 ngOnInit().

的原因
ngOnInit() {  
    this.myId =2;    /* ur id */

    let index = this._tradesmen.findIndex(x => x.id == this.myId);

    if(index>=0){    /* if there is value in the array that matches the id value*/
      this.tradesman = this._tradesmen[index];
    } 
  }

您无需更改 html 文件中的任何内容。

  <select [(ngModel)]="tradesman">
    <option>Select</option>
    <option [ngValue]="v" *ngFor='let v of _tradesmen'>{{ v.firstname }} {{ v.lastname }}</option>
  </select>