How can I get new selection in "select" in Angular 2? How can I get new selection in "select" in Angular 2? angular angular

How can I get new selection in "select" in Angular 2?


If you don't need two-way data-binding:

<select (change)="onChange($event.target.value)">    <option *ngFor="let i of devices">{{i}}</option></select>onChange(deviceValue) {    console.log(deviceValue);}

For two-way data-binding, separate the event and property bindings:

<select [ngModel]="selectedDevice" (ngModelChange)="onChange($event)" name="sel2">    <option [value]="i" *ngFor="let i of devices">{{i}}</option></select>
export class AppComponent {  devices = 'one two three'.split(' ');  selectedDevice = 'two';  onChange(newValue) {    console.log(newValue);    this.selectedDevice = newValue;    // ... do other stuff here ...}

If devices is array of objects, bind to ngValue instead of value:

<select [ngModel]="selectedDeviceObj" (ngModelChange)="onChangeObj($event)" name="sel3">  <option [ngValue]="i" *ngFor="let i of deviceObjects">{{i.name}}</option></select>{{selectedDeviceObj | json}}
export class AppComponent {  deviceObjects = [{name: 1}, {name: 2}, {name: 3}];  selectedDeviceObj = this.deviceObjects[1];  onChangeObj(newObj) {    console.log(newObj);    this.selectedDeviceObj = newObj;    // ... do other stuff here ...  }}

Plunker - does not use <form>
Plunker - uses <form> and uses the new forms API


You can pass the value back into the component by creating a reference variable on the select tag #device and passing it into the change handler onChange($event, device.value) should have the new value

<select [(ng-model)]="selectedDevice" #device (change)="onChange($event, device.value)">    <option *ng-for="#i of devices">{{i}}</option></select>onChange($event, deviceValue) {    console.log(deviceValue);}


Just use [ngValue] instead of [value]!!

export class Organisation {  description: string;  id: string;  name: string;}export class ScheduleComponent implements OnInit {  selectedOrg: Organisation;  orgs: Organisation[] = [];  constructor(private organisationService: OrganisationService) {}  get selectedOrgMod() {    return this.selectedOrg;  }  set selectedOrgMod(value) {    this.selectedOrg = value;  }}<div class="form-group">      <label for="organisation">Organisation      <select id="organisation" class="form-control" [(ngModel)]="selectedOrgMod" required>        <option *ngFor="let org of orgs" [ngValue]="org">{{org.name}}</option>      </select>      </label></div>