Rodrigo Real
Rodrigo Real

Reputation: 3043

Call a method when the value is changed using Angular 2

How can i call a method when the value is changed using Angular 2?

 <select [(ngModel)]="searchMonster">
     <option>36</option>
     <option>37</option>
 </select>

I tried to use ng-change but had no success.

Upvotes: 8

Views: 27518

Answers (2)

Pardeep Jain
Pardeep Jain

Reputation: 86720

Basically upto my observations [(ngModel)] is called when we have to use two way data Binding in angular. so view and controller/method is called via binding. we can use [(ngModel)] as [ngModel] and (ngModelChange) for change detection but in This case onChange() gets called twice for each select list change that way according to this answer here but as you want to call a method on change you can use this way here:-

<select [(ngModel)]="selectedDevice" #device (change)="onChange(device.value)">
    <option *ngFor="#i of devices">{{i}}</option>
</select>

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

i found best answer to this question is this

Upvotes: 8

Murhaf Sousli
Murhaf Sousli

Reputation: 13286

Use ngModelChange. check the template syntax docs.

try this

<select
  [ngModel]="searchMonster"
  (ngModelChange)="yourMethod($event)">
     <option>36</option>
     <option>37</option>
</select>

an alternative worked with me for <input> tag, try this for <select>

<select #option
  [ngModel]="searchMonster"
  (ngModelChange)="yourMethod(option.value)">
     <option>36</option>
     <option>37</option>
</select>    

Upvotes: 9

Related Questions