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