首页 文章

Angular2 - 更新选择框更改的值

提问于
浏览
0

当用户在选择框中选择新选项时,我正在尝试获取新值 .

现在,我在 onSubmitonFooChange 两种情况下都收到了未定义,我有点可以理解为什么,因为 b 只是在调用之后在线定义 .

我已经看到一些不同的方法来更新选择框中的值,但到目前为止,我实际上无法解决这个问题 .

你能就如何解决这个问题给我一个建议吗?

class Foo {
    constructor(
        bar: string;
    ) {}
}

foo: foo = new Foo(
    'someValueWillCome'
)
onFooChange(newBar) {
    this.foo.bar = newBar
}
onSubmit() {
    console.log('onSubmit: ', this.foo);
}

<form (ngSubmit)="onSubmit()" #fooForm="ngForm">
  <label>Location</label>
  <select [(ngModel)]="foo.bar" ngControl="bar" (click)="onFooChange(b)">
    <option *ngFor="#b of aListOfBars" [value]="b">{{b}}</option>
  </select>           
<button type="submit">Submit</button>
<form>

换句话说:如何获取所选的选项值?


我设法使用 $event.target.value ,但必须是一个有角度的方式来解决这个问题 .

<select [(ngModel)]="foo.bar" ngControl="bar" (click)="onFooChange($event.target.value)">
    <option *ngFor="#b of aListOfBars" [value]="b">{{b}}</option>

通过将Angular从2.0.15更新到2.0.17来解决

2 回答

  • 0

    这是最近修复的Firefox和IE的已知问题

    https://github.com/angular/angular/pull/8148

  • 1

    我不确定我是否正确理解你;如果用户选择了其他选项,则 foo.bar 中的值将更改为 <select> ,通过 [(ngModel)]="foo.bar" ;你已经拥有了新的 Value .

相关问题