Angular 2 filter/search list

前端 未结 12 1411
眼角桃花
眼角桃花 2020-11-27 14:25

I\'m looking for the angular 2 way to do this.

I simply have a list of items, and I want to make an input whos job is to filter the list.



        
12条回答
  •  天命终不由人
    2020-11-27 14:52

    You have to manually filter result based on change of input each time by keeping listener over input event. While doing manually filtering make sure you should maintain two copy of variable, one would be original collection copy & second would be filteredCollection copy. The advantage for going this way could save your couple of unnecessary filtering on change detection cycle. You may see a more code, but this would be more performance friendly.

    Markup - HTML Template

    
    
    
    {{item.name}}

    Code

    assignCopy(){
       this.filteredItems = Object.assign([], this.items);
    }
    filterItem(value){
       if(!value){
           this.assignCopy();
       } // when nothing has typed
       this.filteredItems = Object.assign([], this.items).filter(
          item => item.name.toLowerCase().indexOf(value.toLowerCase()) > -1
       )
    }
    this.assignCopy();//when you fetch collection from server.
    

提交回复
热议问题