2016-09-28 6 views
4

[ngValue]を使用して、コンポーネントのPersonプロパティにバインドされた選択リストがあります。選択を変更すると、underyling selectedPersonプロパティが期待通りに更新されます。ただし、選択した人物をコードで変更すると、初期化時に選択された人物にはデフォルトが適用されず、更新もされません。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にバインドすることもできますが、それはIDと名前が同期しなくなることを意味します。他のいくつかの問題をデバッグしようとする開発者にとっては非常に混乱している可能性があります。 – Nemir

+0

'[attr.selected] =" p.personId === selectedPerson?.personId?true:null "'正しい '

+0

'selected'属性は' ngModel'では動作しません。 – rinukkusu

関連する問題