0
<input type="text" [(ngModel)]="searchTerm" (input)="search()">

We type something to search the first time it gets searched but again if we search then no records are found because the original array records is changed it would only consist of the records which are searched and not all the records how to deal with this problem.

I could create a second array to keep a copy of all the records and assign it to the original array in the else if condition but that would only work if we empty the search box and not if we search and type again without emptying the search box to the last character.

The records are shown in the table with ngfor. The search function is for that table

 searchTerm : any;
    records: any;  //array of objects

    search(){
 if(this.searchTerm !== ""){
     this.records = this.records.filter((res: any)=>{
            return (res.name && res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase()));
          });
} else if(this.searchTerm === "") {

}
    }
zuyi
  • 459
  • 2
  • 8
  • 17
venabeo
  • 69
  • 6

2 Answers2

1

Your objects are in this.records and when you do search you assign the result again to the same variable this.records. The next time you search, you won't get it because the items does not exist in the array. Create another array for search results.

this.filteredRecords = this.records.filter((res: any)=>{
    return (res.name && res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase()));
});

And depends how you handle for different user cases. When you search you show fiteredRecords which contains results returned from your filter function, and in normal user case or searchTerm is empty:

else if(this.searchTerm === "") {
 this.filteredRecords = this.records
}
Maihan Nijat
  • 9,054
  • 11
  • 62
  • 110
0

Angular pipes are best solution for this scenario. Create a pipe for search it will filter and render filtered array in DOM but will not update your original array

Angular Pipe

Similar Question

Ravin Singh D
  • 904
  • 10
  • 19