【问题标题】:Angular2 two-way binding to select option not updatingAngular2双向绑定选择选项不更新
【发布时间】: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


【解决方案1】:

问题是,通过使用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

【讨论】:

  • 谢谢。这清楚地解释了问题并给了我一个解决方案。必须将 selectedPerson 对象引用更新为与列表中的引用相同确实感觉有点痛苦,但实际上,这些值将来自单独的 http 调用。因此,我需要包括一个额外的步骤来对齐我的应用程序中每个选择列表的引用。我可以绑定到 id 而不是这样可以工作,但这意味着 is 和 name 会不同步;对于尝试调试其他问题的开发人员来说,这可能会非常令人困惑。
  • 再想一想,[attr.selected]="p.personId === selectedPerson?.personId ? true : null" 表达式不应该处理选择正确的&lt;option&gt; 吗?
  • selected 属性不适用于ngModel
  • 不!不!不!,ng2 团队应该改变这种模式,不应该只按对象选择,因为 html 本身不能与对象一起使用。
  • 我已经搜索了几个小时,也遇到了同样的问题。参考...为什么我没有想到...谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-07
  • 1970-01-01
  • 1970-01-01
  • 2016-06-13
  • 1970-01-01
相关资源
最近更新 更多