HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptangularCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
angularhowselectselectioncannewget

Problem

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?


{{i}}



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

Solution

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


{{i}}

onChange(deviceValue) {
console.log(deviceValue);
}


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


{{i}}





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:


{{i.name}}

{{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 `

Plunker - uses
` and uses the new forms API

Context

Stack Overflow Q#33700266, score: 959

Revisions (0)

No revisions yet.