Search code examples
angularionic-frameworkionic2ionic3searchbar

Ion-SearchBar not working properly


i have an array that i use to populate and i'm using the ion search-bar so the user can search for an item on the list but the problem is when the user backspaces or erases what they were searching for the list doesn't go back to its original state

Code Below:

<ion-searchbar  (ionInput)="setFilteredItems()" placeholder="Search"
                [(ngModel)]="searchTerm">
</ion-searchbar>

Filtering Function:

filterItems(searchTerms){
    return this.categories.filter((item)=>{
      return item.category_name.toLowerCase().indexOf(searchTerms.toLowerCase())>-1;
    })

    setFilteredItems(){
        this.categories = this.filterItems(this.searchTerm);
    }
}

Solution

  • Try this code:

    //Maintain a copy of data on which needs a search
    this.searchListCopy = JSON.parse(JSON.stringify(this.categories));
    
    protected search = () => {
        this.resetChanges();
    
        this.categories = this.categories.filter((item)=>{
            return item.category_name.toLowerCase().indexOf(searchTerms.toLowerCase())>-1;
        })
    };
    
    protected resetChanges = () => {
        this.categories = this.searchListCopy;
    };
    

    HTML will be like:

    <ion-searchbar class="searchIcon" [(ngModel)]="searchKey" [showCancelButton]="false" (ionInput)="search()" (ionClear)="resetChanges()">
    </ion-searchbar>