How to apply filters to *ngFor?

前端 未结 23 1249
無奈伤痛
無奈伤痛 2020-11-22 03:44

Apparently, Angular 2 will use pipes instead of filters as in Angular1 in conjunction with ng-for to filter results, although the implementation still seems to be vague, wit

23条回答
  •  情深已故
    2020-11-22 03:49

    This is your array

    products: any = [
            {
                "name": "John-Cena",
                        },
            {
                "name": "Brock-Lensar",
    
            }
        ];
    

    This is your ngFor loop Filter By :

    
        
    • {{product.name }}

    There I'm using filterProduct instant of products, because i want to preserve my original data. Here model _filterText is used as a input box.When ever there is any change setter function will call. In setFilterText performProduct is called it will return the result only those who match with the input. I'm using lower case for case insensitive.

    filterProduct = this.products;
    _filterText : string;
        get filterText() : string {
            return this._filterText;
        }
    
        set filterText(value : string) {
            this._filterText = value;
            this.filterProduct = this._filterText ? this.performProduct(this._filterText) : this.products;
    
        } 
    
        performProduct(value : string ) : any {
                value = value.toLocaleLowerCase();
                return this.products.filter(( products : any ) => 
                    products.name.toLocaleLowerCase().indexOf(value) !== -1);
            }
    

提交回复
热议问题