我有一個選擇列表綁定到我的組件上的人物業使用[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
可能重複的[角2 - 綁定對象下拉並選擇基於事件的值](http://stackoverflow.com/questions/39105905/angular-2-bind-object-to-dropdown-並選擇基於事件的值) –