我有一个选择列表绑定到我的组件上的人物业使用[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-并选择基于事件的值) –