Angular 2 filter/search list

前端 未结 12 1404
眼角桃花
眼角桃花 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:42

    This code nearly worked for me...but I wanted a multiple element filter so my mods to the filter pipe are below:

    import { Pipe, PipeTransform, Injectable } from '@angular/core';
    
    @Pipe({ name: 'jsonFilterBy' })
    @Injectable()
    export class JsonFilterByPipe implements PipeTransform {
    
      transform(json: any[], args: any[]): any[] {
        const searchText = args[0];
        const jsonKey = args[1];
        let jsonKeyArray = [];
    
        if (searchText == null || searchText === 'undefined') { return json; }
    
        if (jsonKey.indexOf(',') > 0) {
            jsonKey.split(',').forEach( function(key) {
                jsonKeyArray.push(key.trim());
            });
        } else {
            jsonKeyArray.push(jsonKey.trim());
        }
    
        if (jsonKeyArray.length === 0) { return json; }
    
        // Start with new Array and push found objects onto it.
        let returnObjects = [];
        json.forEach( function ( filterObjectEntry ) {
    
            jsonKeyArray.forEach( function (jsonKeyValue) {
                if ( typeof filterObjectEntry[jsonKeyValue] !== 'undefined' &&
                filterObjectEntry[jsonKeyValue].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
                    // object value contains the user provided text.
                    returnObjects.push(filterObjectEntry);
                    }
                });
    
        });
        return returnObjects;
      }
    } 
    

    Now, instead of

    jsonFilterBy:[ searchText, 'name']
    

    you can do

    jsonFilterBy:[ searchText, 'name, other, other2...']
    

提交回复
热议问题