Angular2双向绑定以选择选项不更新 [英] Angular2 two-way binding to select option not updating
问题描述
我有一个选择列表,该列表使用[ngValue]绑定到组件上的Person属性.当我更改选择内容时,将按预期更新底层样式的selectedPerson属性.但是,如果在代码中更改所选人员,则select不会在初始化时默认为所选人员,也不会更新.
I have a select list that is bound to an Person property on my component using [ngValue]. When I change the select, the underyling selectedPerson property is updated as expected. However, the select does no default to the selected person on initialisation nor does it update if I change the selected person in code.
对我所缺少的任何帮助将不胜感激.这是我的代码...
Any help into what I am missing would be greatly appreciated. Here's my code...
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 {}
...这是一个柱塞 http://plnkr.co/edit/ag94mZO9Zggg1kZx8jJV >
...and here's a Plunker http://plnkr.co/edit/ag94mZO9Zggg1kZx8jJV
推荐答案
问题是,通过使用ngValue
,select
期望使用相同的引用,而不仅仅是看起来相似的对象.
The problem is, that by using ngValue
, the select
expects the same reference, not just a similar looking object.
您可以添加一种通过名称进行选择的方法,如下所示:
You could add a method to select by name like this:
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");
}
您更新的柱塞
这篇关于Angular2双向绑定以选择选项不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!