Jonas Praem
Jonas Praem

Reputation: 2454

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. 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.

Upvotes: 1

Views: 11025

Answers (2)

Tomasz Kula
Tomasz Kula

Reputation: 16847

Change ([ngModel])="selectedValue" to [(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. You can split your two way binding into [ngModel] and (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

Upvotes: 5

Ramesh Rajendran
Ramesh Rajendran

Reputation: 38683

Please change the definition of ([ngModel]) to [(ngModel)] and you should initialize the objects values before assign the value in selectedValue object

Upvotes: 0

Related Questions