4

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);
    }
}

2 Answers 2

6

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

There is another output property called ionClear fired when the backspace button is clicked.

you can use it like this:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.