Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 ngModelChange select option, grab a specific property

Tags:

angular

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)); } 
like image 419
ClickThisNick Avatar asked Mar 13 '16 14:03

ClickThisNick


People also ask

What is the difference between ngModel and ngModelChange?

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.

Can I use ngModelChange without ngModel?

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.

What is the purpose of the ngModelChange event property?

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 .


2 Answers

<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

like image 59
Nikhil Shah Avatar answered Sep 24 '22 03:09

Nikhil Shah


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> 
like image 41
Roman Gural Avatar answered Sep 24 '22 03:09

Roman Gural