I have a dropdown select form in angular 2.
Currently: When I select an option the option name
gets passed into my onChange
function as $event
Wanted: When I select an option I would like to pass workout.id
into my onChange
function.
How can I achieve that?
<select class="form-control" [ngModel]="selectedWorkout" (ngModelChange)="onChange($event)"> <option *ngFor="#workout of workouts">{{workout.name}}</option> </select>
Controller
onChange(value){ alert(JSON.stringify(value)); }
The NgModel class has the update property with an EventEmitter instance bound to it. This means we can't use (ngModelChange) without ngModel . Whereas the (change) event can be used anywhere, and I've demonstrated that above with the [value] property binding instead.
When the user wants to change the model, by entering text into the input, the event callback fires and sets the new value to the model. We can't use mgModelChange without ngModel because the ngModel class has update function with EventEmitter instance.
ngModelChange event parameter contains the changed value. If we use two way binding syntax for ngModel the value will be updated. So the default (ngModelChange) function will update the value of ngModel property. i.e., user.Name .
<select class="form-control" [ngModel]="selectedWorkout" (ngModelChange)="onChange($event)"> <option *ngFor="#workout of workouts" [value]="workout.id">{{workout.name}}</option> </select>
OR
<select class="form-control" [(ngModel)]="selectedWorkout" (change)="onChange($event.target.value)"> <option *ngFor="#workout of workouts" [value]="workout.id" >{{workout.name}}</option> </select>
check this
you could also use [ngValue] inside option:
<select class="form-control" [ngModel]="selectedWorkout" (ngModelChange)="onChange($event)"> <option *ngFor="#workout of workouts" [ngValue]="workout">{{workout.name}}</option> </select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With