Searchbar issue with event keypress or keyup

I would like to know if I am the only one that noticed that when calling a function for keypress or keyup, the first time the character entered is not returned. The second character entered will trigger again the function, but with the previous character.

  <ion-searchbar primary [(ngModel)]="searchQuery" 
                  (keyup)="updateList()"
                  show-cancel="true" 
                  placeholder="Search">
  </ion-searchbar>

If I change it for “input” instead of “keyup” it works. Normal behavior?

The keyup event is coming from the input field itself, the input event is a custom event emitted by the Searchbar. When you use the keyup event you can pass $event and then grab the value from that to get the actual value at the time. For example:

In your HTML:

<ion-searchbar primary [(ngModel)]="searchQuery" 
               (keyup)="updateList($event)"
               show-cancel="true" 
               placeholder="Search">
</ion-searchbar>

and then in the JS:

updateList(ev) {
  console.log(ev.target.value);
}

and this will print the correct value. The Searchbar overrides the input event on the input itself in order to pass the searchbar itself back on input change. input gets triggered on keyup of the input and when clicking the clear/cancel button.

So to answer your question - yes this is the normal behavior (to my knowledge): https://angular.io/docs/js/latest/guide/user-input.html

4 Likes

Thanks @brandyshea, I now understand and it is working :smile:

@brandyshea : How can i use keypress event. I want event.charCode value from keypress which is not possible in keyup, keydown, ionInput event.

can you help me ?

1 Like