1

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.

Jonas Praem
  • 2,296
  • 5
  • 32
  • 53

2 Answers2

5

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

Tomasz Kula
  • 16,199
  • 2
  • 68
  • 79
  • Use Template reference variable instead of passing entire event ,[Passing `$event` is a dubious practice](https://angular.io/guide/user-input#passing-event-is-a-dubious-practice) – Vikas Apr 19 '18 at 10:14
  • 1
    In this case `$event` is an Angular Event. Not a DOM event. It is just a number. So your link does not apply. It is no different than any other event emitted by the `@Output` decorator. – Tomasz Kula Apr 19 '18 at 10:16
  • 1
    thanx for the info :) – Vikas Apr 19 '18 at 10:40
  • 1
    Also, remember to import the `FormsModule` into your module so you can use the `[(ngModel)]` directive. – TetraDev Apr 14 '20 at 00:16
0

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

Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234