Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 ngModel value not updating fast enough using ionic

I have a ion-searchbar that looks like this

<ion-searchbar [(ngModel)]="searchQuery" (keyup.enter)="search();"></ion-searchbar>

and the searchQuery is defined in my typescript file like this

export class SearchPage {
  searchQuery: string; 

  constructor(){}

  search() {
   this.service.search(this.searchQuery).subscribe(
     data => this.searchResults = data,
     error => {
       //something
     }, () => {
       //something
     }
   );
  }
 }

The problem is that if I change the value too fast and I press Enter, the value of searchQuery is not updated. For example, if I search "test" and I wait two seconds it will work. If I then search "testing" and I type it fast and press Enter right away, the value will still be "test". Now, I know this sounds weird, but it is really happening!

Any ideas why the value is not changed as soon as I type something?

Thank you

like image 625
Marc-André Therrien Avatar asked Jun 30 '16 16:06

Marc-André Therrien


2 Answers

In Html try this event change

  <form [ngFormModel]="searchForm" (ngSubmit)="search()">
      <ion-searchbar [(ngModel)]="searchQuery" (keyup)="search()"></ion-searchbar>
        <button type="submit" block>Submit</button>
   </form>

Even check here might this help

In ts trim the value

  this.service.search(this.searchQuery.trim()).subscribe(.....)
like image 175
mayur Avatar answered Nov 17 '22 19:11

mayur


This is how I did it, based on the documentation for ion-searchbar:

<ion-searchbar #searchBar [debounce]="50" (ionChange)="search(searchBar.value)">
</ion-searchbar>

and in the TS file:

search(value: string) {
    // do something with value
}

Explanation:

It's pretty self-explanatory, but here it is. The #searchBar creates a 'hook' for the element (sort of a 'self', or 'this', but named). We then use the property value from ion-searchbar to pass it to our function. The last thing is modifying the [debounce] property to make it update faster (but it will trigger more times when people write fast - use with discretion).

like image 2
tfrascaroli Avatar answered Nov 17 '22 19:11

tfrascaroli