简体   繁体   English

角5:选择元素上的ngModel绑定不会更新

[英]Angular 5: ngModel binding on select element doesn't update

I have this markup for a select element: 我有一个选择元素的标记:

<select type="submit" ([ngModel])="selectedValue" #item (change)="onSelectItem(item.value)">
                <option>Pick an option</option>
                <option *ngFor="let object of objects">{{ object.value }}</option>
</select>

When I update the ngModel binding from typescript, nothing happens. 当我从打字稿更新ngModel绑定时,什么也没发生。 Essentially I am just doing this, in the component: 本质上,我只是在组件中这样做:

ngOnInit() {
  this.selectedValue = 'something' // One of the options from the list of objects
}

However, nothing happens. 但是,没有任何反应。 The value I am trying to update it to, are in the list of objects (in the *ngFor) - if that matters. 我尝试将其更新为的值在对象列表中(在* ngFor中)-如果重要的话。

Change ([ngModel])="selectedValue" to [(ngModel)]="selectedValue" ([ngModel])="selectedValue"更改为[(ngModel)]="selectedValue"

Just like the docs say: 就像文档说的那样:

Visualize a banana in a box to remember that the parentheses go inside the brackets. 可视化框中的香蕉,以记住括号放在括号内。

Also you do not need the (change) listener if you are using ngModel . 另外,如果您使用的是ngModel则不需要(change)侦听ngModel You can split your two way binding into [ngModel] and (ngModelChange) 您可以将两种绑定方式分为[ngModel](ngModelChange)

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
  <select type="submit" [ngModel]="selectedValue" (ngModelChange)="onSelectedChange($event)">
    <option *ngFor="let option of options">{{ option }}</option>
  </select>

  {{ selectedValue }}
  ` ,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  selectedValue = 1;
  options = [1,2,3]

  onSelectedChange(value: number) {
    // do something else with the value
    console.log(value);

    // remember to update the selectedValue
    this.selectedValue = value;
  }
}

Live demo 现场演示

请将([ngModel])的定义更改为[(ngModel)]并且应在初始化selectedValue对象中的值之前初始化objects

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM