Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a method when the value is changed using Angular 2

Tags:

angular

ionic

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.

like image 217
Rodrigo Real Avatar asked Dec 23 '15 02:12

Rodrigo Real


2 Answers

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>    
like image 72
Murhaf Sousli Avatar answered Sep 29 '22 23:09

Murhaf Sousli


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

like image 42
Pardeep Jain Avatar answered Sep 29 '22 22:09

Pardeep Jain