2016-09-28 58 views
4

我有一個選擇列表綁定到我的組件上的人物業使用[ngValue]。當我改變選擇時,undererling selectedPerson屬性按預期更新。但是,select在初始化時不會對選定的人員進行默認設置,如果我更改了代碼中的選定人員,它也不會更新。Angular2雙向綁定選擇選項不更新

任何幫助到我失蹤將不勝感激。這裏是我的代碼...

import {Component, OnInit, NgModule} from '@angular/core' 
import {BrowserModule} from '@angular/platform-browser' 
import { FormsModule } from '@angular/forms'; 

@Component({ 
    selector: 'my-app', 
    template: ` 
     <form> 
      <select [(ngModel)]="selectedPerson" 
        name="selectedPerson"> 
       <option [ngValue]="null">Please choose...</option> 
       <option *ngFor="let p of people" 
         [ngValue]="p" 
         [attr.selected]="p.personId === selectedPerson?.personId ? true : null ">{{p.name}}</option> 
      </select> 
      <p>The selected person is {{selectedPerson?.name}}</p> 
      <button type="button" (click)="selectJane()">Select Jane</button> 
      <button type="button" (click)="clearSelection()">Clear Selection</button> 
     </form>`, 
}) 
export class App implements OnInit { 

    public ngOnInit() { 

    this.people = [ 
     { personId: 1, name: "Tom" }, 
     { personId: 2, name: "Mary" }, 
     { personId: 3, name: "Jane" } 
    ] 
    this.selectedPerson = { personId: 2, name: "Mary" } 
    } 

    public people: Person[]; 
    public selectedPerson: Person; 

    public selectJane(){ 
    this.selectedPerson = { personId: 3, name: "Jane" } 
    } 

    public clearSelection(){ 
    this.selectedPerson = null; 
    } 
} 

export class Person { 
    public personId: number; 
    public name: string; 
} 

@NgModule({ 
    imports: [ BrowserModule, FormsModule ], 
    declarations: [ App ], 
    bootstrap: [ App ] 
}) 
export class AppModule {} 

...這是一個Plunker http://plnkr.co/edit/ag94mZO9Zggg1kZx8jJV

+0

可能重複的[角2 - 綁定對象下拉並選擇基於事件的值](http://stackoverflow.com/questions/39105905/angular-2-bind-object-to-dropdown-並選擇基於事件的值) –

回答

6

的問題是,通過使用ngValue,該select預計相同的參考,而不僅僅是一個外觀類似的對象。

你可以像這樣添加一個方法來選擇按名稱:

public selectByName(name: string) { 
    this.selectedPerson = this.people.find(person => person.name === name); 
} 

然後調用它在你的ngOnInit()

this.selectByName("Mary"); 
// or this.selectedPerson = this.people[2]; 

而且在selectJane()

public selectJane(){ 
    this.selectByName("Jane"); 
} 

您的已更新Plunker

+1

謝謝。這清楚地解釋了問題並給了我一個解決方案。必須將selectedPerson對象的引用更新爲與列表中的引用相同,不過感覺有點痛苦,但實際上,這些值將來自單獨的http調用。因此,我需要包括一個額外的步驟來對齊應用中每個選擇列表的引用。我可以綁定到ID,而不是那將工作,但這將意味着是和名稱會失去同步;這對於試圖調試其他問題的開發人員來說可能會非常困惑。 – Nemir

+0

想想這個更多,不應該''[attr.selected] =「p.personId === selectedPerson?.personId?true:null」'處理保持正確的'

+0

'selected'屬性不適用於'ngModel'。 – rinukkusu