【发布时间】:2017-02-06 07:45:16
【问题描述】:
我有一个选择列表,它使用 [ngValue] 绑定到我的组件上的 Person 属性。当我更改选择时,underyling selectedPerson 属性按预期更新。但是,如果我在代码中更改选定的人,则选择不会在初始化时默认为选定的人,也不会更新。
对我所缺少的任何帮助将不胜感激。这是我的代码...
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
【问题讨论】:
标签: angular typescript binding