Angular2双向绑定选择选项不更新

时间:2016-09-28 11:02:30

标签: angular typescript binding

我有一个选择列表,它使用[ngValue]绑定到组件上的Person属性。当我更改选择时,underyling selectedPerson属性将按预期更新。但是,如果我在代码中更改所选人员,则select在初始化时不会默认为所选人员。

对我所缺少的任何帮助都将不胜感激。这是我的代码......

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

1 个答案:

答案 0 :(得分:7)

问题是,通过使用ngValueselect需要相同的引用,而不仅仅是类似的对象。

您可以添加一个方法来按名称选择:

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