Created
March 2, 2017 21:37
-
-
Save dpedro/adeadb818e5011b527579c3c9b813c5a to your computer and use it in GitHub Desktop.
Get selected value from select
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ... | |
} | |
} | |
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 #device (change)="onChange($event, device.value)"> | |
<option *ng-for="#i of devices">{{i}}</option> | |
</select> | |
onChange($event, deviceValue) { | |
console.log(deviceValue); | |
} | |
// Using ngModel | |
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> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment