Angular 2 filter/search list

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

    Slight modification to @Mosche answer, for handling if there exist no filter element.

    TS:

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
        name: 'filterFromList'
    })
    export class FilterPipe implements PipeTransform {
        public transform(value, keys: string, term: string) {
    
            if (!term) {
                return value
            }
            let res = (value || []).filter((item) => keys.split(',').some(key => item.hasOwnProperty(key) && new RegExp(term, 'gi').test(item[key])));
            return res.length ? res : [-1];
    
        }
    }
    

    Now, in your HTML you can check via '-1' value, for no results.

    HTML:

    {{item}}

    No Matches

提交回复
热议问题