I am using Angular 2 (TypeScript).
I want to do something with the new selection, but what I get in onChange() is always the last selection. How can I get the new selection?
<select [(ngModel)]="selectedDevice" (change)="onChange($event)">
<option *ngFor="#i of devices">{{i}}</option>
</select>
onChange($event) {
console.log(this.selectedDevice);
// I want to do something here with the new selectedDevice, but what I
// get here is always the last selection, not the one I just selected.
}
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>
I ran into this problem while doing the Angular 2 forms tutorial (TypeScript version) at https://angular.io/docs/ts/latest/guide/forms.html
The select/option block wasn't allowing the value of the selection to be changed by selecting one of the options.
Doing what Mark Rajcok suggested worked, although I'm wondering if there's something I missed in the original tutorial or if there was an update. In any case, adding
onChange(newVal) {
this.model.power = newVal;
}
to hero-form.component.ts in the HeroFormComponent class
and
(change)="onChange($event.target.value)"
to hero-form.component.html in the <select> element made it work
use selectionChange in angular 6 and above. example
(selectionChange)= onChange($event.value)
I was has same problem and i solved using the below code :
(change)="onChange($event.target.value)"
In Angular 8 you can simply use "selectionChange" like this:
<mat-select [(value)]="selectedData" (selectionChange)="onChange()" >
<mat-option *ngFor="let i of data" [value]="i.ItemID">
{{i.ItemName}}
</mat-option>
</mat-select>
Angular 7/8
As of angular 6,the use of ngModel input property with reactive forms directive have been deprecated and removed altogether in angular 7+. Read official doc here.
Using reactive form approach you can get/set selected data as;
//in your template
<select formControlName="person" (change)="onChange($event)"class="form-control">
<option [value]="null" disabled>Choose person</option>
<option *ngFor="let person of persons" [value]="person">
{{person.name}}
</option>
</select>
//in your ts
onChange($event) {
let person = this.peopleForm.get("person").value
console.log("selected person--->", person);
// this.peopleForm.get("person").setValue(person.id);
}
Another option is to store the object in value as a string:
<select [ngModel]="selectedDevice | json" (ngModelChange)="onChange($event)">
<option [value]="i | json" *ngFor="let i of devices">{{i}}</option>
</select>
component:
onChange(val) {
this.selectedDevice = JSON.parse(val);
}
This was the only way I could get two way binding working to set the select value on page load. This was because my list that populates the select box was not the exact same object as my select was bound to and it needs to be the same object, not just same property values.
If you don't need two-way data-binding:
<select (change)="updateSorting($event)">
<option disabled selected>Sorting</option>
<option value="pointDes">pointDes</option>
<option value="timeDes">timeDes</option>
<option value="timeAsc">timeAsc</option>
<option value="pointAsc">pointAsc</option>
</select>
updateSorting(e: any) {
// console.log((e.target as HTMLSelectElement)?.value); // also work
console.log(e.target.value);
}
<mat-form-field>
<mat-select placeholder="Vacancies" [(ngModel)]="vacanciesSpinnerSelectedItem.code" (ngModelChange)="spinnerClick1($event)"
[ngModelOptions]="{standalone: true}" required>
<mat-option *ngFor="let spinnerValue of vacanciesSpinnerValues" [value]="spinnerValue?.code">{{spinnerValue.description}}</mat-option>
</mat-select>
I used this for angular Material dropdown. works fine
I tried all the suggestions and nothing works for me.
Imagine the situation: you need a 2-way binding and you have a lookup with NUMBER values and you want to fill your SELECT with the values from this lookup and highlight the chosen option.
Using [value] or (ngModelChange) is a no-go, because you won't be able to select the chosen option after user initiated the change: [value] considers everything a string, as to (ngModelChange) - it obviously should not be used when user initiates the change, so it ruins the proper selection. Using [ngModel] guarantees the fixed format of received VALUE as INDEX: VALUE and it's easy to parse it correspondingly, HOWEVER once again - it ruins the selected option.
So we go with [ngValue] (which will take care of proper types), (change) and... [value], which guarantees the handler receives VALUE, not a DISPLAYED VALUE or INDEX: VALUE :) Below is my working clumsy solution:
<select
class="browser-default custom-select"
(change)="onEdit($event.target.value)"
>
<option [value]="">{{
'::Licences:SelectLicence' | abpLocalization
}}</option>
<ng-container *ngIf="licencesLookupData$ | async">
<option
*ngFor="let l of licencesLookupData$ | async"
[ngValue]="l.id"
[value]="l.id"
[selected]="l.id == selected.id"
>
{{ l.id }} {{ l.displayName | defaultValue }}
</option>
</ng-container>
</select>
onEdit(idString: string) {
const id = Number(idString);
if (isNaN(id)) {
this.onAdd();
return;
}
this.licencesLoading = true;
this.licencesService
.getById(id)
.pipe(finalize(() => (this.licencesLoading = false)), takeUntil(this.destroy))
.subscribe((state: Licences.LicenceWithFlatProperties) => {
this.selected = state;
this.buildForm();
this.get();
});
}
latest ionic 3.2.0 have modified (change) to (ionChange)
eg:
HTML
<ion-select (ionChange)="function($event)"> <ion-option>1<ion-option>
</ion-select>
TS
function($event){
// this gives the selected element
console.log($event);
}
In Angular 5 I did with the following way. get the object $event.value instead of $event.target.value
<mat-form-field color="warn">
<mat-select (ngModelChange)="onChangeTown($event)" class="form-width" formControlName="branch" [(ngModel)]="branch" placeholder="Enter branch">
<mat-option *ngFor="let branch of branchs" [value]="branch.value">
{{ branch.name }}
</mat-option>
</mat-select>
</mat-form-field>
onChangeTown(event): void {
const selectedTown = event;
console.log('selectedTown: ', selectedTown);
}
I am displaying a few objects inside a select. But I want to show the user something different after selection than while picking his/her option.
Is that even possible in Angular as it is in WPF?
My select looks like this:
<select class="vstatus-select" [(ngModel)]="rezept.kunde.versichertenstatus1" name="kunde_vstatus1">
<option *ngFor="let vstatus of versichertenstatus1"[ngValue]="vstatus">
{{vstatus.name}} - {{vstatus.kennung}}
</option>
</select>
The Model:
export interface IVersichertenstatus{
name: string;
kennung: string;
}
The Key Problem is, that I want to show "kennung" and "name" while picking an option and only "kennung" afterwards.
I also need ngValue to be the whole object and not just "kennung".
Cheers
You can try this.
<select class="vstatus-select" [(ngModel)]="rezept.kunde.versichertenstatus1" name="kunde_vstatus1">
<option *ngFor="let vstatus of versichertenstatus1"[ngValue]="vstatus">
<span *ngIf="your-condition-to-show-name">{{vstatus.name}} -</span> {{vstatus.kennung}}
</option>
</select>
I hope this help you, regards
Thanks to #Carles Ramos!
I've set two events - and functions which change a boolean. This boolean is used for the *ngIf tag.
<select class="vstatus-select"
[(ngModel)]="rezept.kunde.versichertenstatus1"
name="kunde_vstatus1"
(focus)="vselect_focus(1)"
(change)="vselect_focusout(1)">
<option *ngFor="let vstatus of versichertenstatus1" [ngValue]="vstatus">
<span *ngIf="selectedVersichertenstatus[0]">
{{vstatus.name}} -
</span>
{{vstatus.kennung}}
</option>
</select>
The events look like this:
public selectedVersichertenstatus:boolean[] = [false, false, false];
vselect_focus(selector:number){
this.selectedVersichertenstatus[selector-1] = true;
}
vselect_focusout(selector:number){
this.selectedVersichertenstatus[selector-1] = false;
}
I want to get the value of the drop-down list in real time.
When I use the following method, I get the desired result.
<template>
<div>
<select id="jsmode" #change="handleOnChange($event)">
<option value="1" selected>one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
</div>
</template>
<script>
export default {
name: 'drop-down-list',
methods: {
handleOnChange: function (e) {
const mode = document.getElementById('jsmode').value
console.log('abcd: ' + mode)
}
}
}
</script>
However, if you divide this into different codes and write them down, only 1 is returned, but the value does not change.
The name of this code is dropdownlist.vue
<template>
<div>
<select id="jsmode" #change="handleOnChange($event)">
<option value="1" selected>one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
</div>
</template>
The name of this code is firestore.dao.js
const mode = document.getElementById('jsmode').value
console.log('abcd: ' + mode)
In this way I separated the code.
There is also a way to use the event bus, but I have been told the following.
Although the selectPosts method works asynchronously, it is not always running, so it is not good to use the event bus to adjust variable values. Use the normal method of calling selectPosts(...some params) by changing only the parameters to be passed.
How can I get the values in real time without using the event bus?
Learning more about AngularJS everyday.
A style contains style.StyleID,style.StyleName,style.EncryptedValue
I have the following code:
<select data-ng-model="StyleID"
data-ng-options="s.StyleID as s.StyleName for s in styles"
data-ng-change="GetOptions()">
<option value="">--Select Style--</option>
</select>
I need to pass EncryptedValue into GetOptions() e.g (GetOptions(EncryptedValue)) or be able to access something like SelectedStyle.EncryptedValue
How do I go about doing that?
UPDATE
Changed my code to:
<select data-ng-model="style"
data-ng-options="s.StyleID as s.StyleName for s in styles"
data-ng-change="GetOptions()">
<option value="">--Select Style--</option>
</select>
My Controller:
$scope.GetOptions = function ()
{
alert($scope.style);
}
alert($scope.style); returns a string of the StyleID
alert($scope.style.StyleID); returns undefined
What is going on ???
Note: styles is loaded via AJAX call (JSON result).
You might have to rework how you handle things in your controller but you can change your model to this:
<select data-ng-model="selectedStyle"
data-ng-options="s as s.StyleName for s in styles"
data-ng-change="GetOptions()">
<option value="">--Select Style--</option>
</select>
Then in your controller, you can do this
$scope.GetOptions = function(){
console.log($scope.selectedStyle.EncryptedValue)
};
The only thing is now if you want to reference your StyleId you have to do it this way:
$scope.selectedStyle.StyleId
<select onchange="showResult(this.value)">
<option value="AAA">London</option>
<option value="BBB">France</option>
<option value="ccc">Berlin</option>
<option value="DDD">Rome</option>
</select>
In above code, the value of each <option> has been passed as parameter in showResult().
My questions is how to pass the content of option element (i.e.'London','France', 'Berlin', 'Rome') as parameter in showResult().
Many Thanks
[yourselect].options[0].text returns 'London', [yourselect].options[1].text France, etc. So, in other words, for every option of an options-nodeList the property text contains its content.
write this code
<select onchange="showResult(this.options[this.selectedIndex])">
<option value="AAA">London</option>
<option value="BBB">France</option>
<option value="ccc">Berlin</option>
<option value="DDD">Rome</option>
</select>
so you will pass the whole selected option node to the showResult function and you will be able to access both the value and text
function showResult(opt) {
alert(opt.value); /* e.g. DDD */
alert(opt.text); /* e.g. Rome */
}
Example Fiddle : http://jsfiddle.net/xypGa/
Try this.options[this.selectedIndex].text, been a while since I did this without jQuery.
function showResult()
{
var value = this.options[this.selectedIndex].value;
var content = this.options[this.selectedIndex].text;
}
Is this question about your issue - Get selected value in dropdown list using JavaScript? ?
in general - document.FORM.FIELDMANE.options[document.FORM.FIELDMANE.selectedIndex].value
in your case it should be i suppose - onchange="showResult(this.options[this.selectedIndex].value)
Instead of passing this.value (the value property of the select element), pass this (the select element), i.e. onchange="showResult(this)", and use code like
function showResult(selectElem) {
var optionText = selectElem.options[selectElem.selectedIndex].text;
alert(optionText); // replace by real code that uses the string
}
An added advantage is that now the function has access to the entire element, so that if you later need to use the value property, too, in the function, you can do that without modifying the function calls.
<select onchange="showResult(this.options[this.selectedIndex].text)">
<option value="AAA">London</option>
<option value="BBB">France</option>
<option value="ccc">Berlin</option>
<option value="DDD">Rome</option>
</select>