Ion-input change not being fired on clearInput

Hi, I have this weird problem. I have a ion-input defined like this:

<ion-input id="songNoId" type="number" clearInput="true" max="999" min = "0" step="1" (ionFocus)="checkFocus($event)" (change)="numberChanged()" (input)="checkInput($event)" [(ngModel)]="myBumber"></ion-input>

As you can see, numberChanged() is supposed to be called, when the value changes. Well, it is. But if I clear the input by clicking the clearInput button (the cross icon on the right side of the input), this function is not called.

This is very weird mostly because I am just not able to google anything on the topic, whereas I would expect there to be a lot of questions on such a basic thing.

What am I doing wrong?

Thanks!

Probably the most pressing thing is binding to an input that isn’t defined. You want (ionChange), not (change). If I were doing a code review, I would also recommend getting rid of the banana binding on ngModel, so that you don’t have multiple bindings on the same event.

Thanks! That indeed helped.

I just noticed the “myBumper” typo - a funny one. It should have been myNumber of course, I was just trying to simplify the line while pasting it here :slight_smile:

However, what you mean by getting rid of the “banana binding” is that I should not bind a variable to ngModel since I am already calling that change function, which can set the variable on it’s own, right?

Yes. To clarify, the “box” binding - [ngModel] is fine, because that’s passing changes from the controller property to the template. The “banana” binding goes the other direction, is duplicated by the (ionChange) handler, and there isn’t a clear guarantee as to the order that they will be called, so you can’t be sure whether you’re looking at the old or new value in the (ionChange) handler.

So, what you actually mean is to do it like this?

<ion-input id="songNoId" type="number" clearInput="true" max="999" min = "0" step="1" (ionFocus)="checkFocus($event)" (ionChange)="numberChanged()" (input)="checkInput($event)" [ngModel]="myNumber"></ion-input>

Is that right? It took me a while to understand. I did not really understand that [()] syntax and I had no idea I could actually write [ngModel] without those parentheses.

More or less, although you probably want to add an $event parameter to the (ionChange) handler in order to get the new value.

Equivalent:

[(ngModel)]="foo"
[ngModel]="foo" (ngModelChange)="foo = $event"

This is how it’s actually implemented internally.

1 Like