invoke pipe when passing function as arg Pipe angu

2019-05-21 19:15发布

I have a list of emplyees and want to make a drop down with predefined department filter

Im trying to make a filter pipe and pass a function as an arg it works only the first time its rendered but I want to invoke the pipe each time the user changes the selection

Pipe:

import { Pipe, PipeTransform, Injectable } from '@angular/core';

  @Pipe({
    name: 'filter'
   })
  @Injectable()
  export class FilterPipe implements PipeTransform {

      transform(value: Array<any>, f) {
             return value.filter(x => f(x));
    }
   }

Component:

     constructor() {

       this.filterFunc = this.filterByDepatment.bind(this);
     }
    //filter function
    filterByDepatment(e) {

   if (this.selectedDepartment > -1) {
        return (e.Departments as Array<any>).find(x => x.Id === this.selectedDepartment);
    } else {
      return true;
     } 
  }

Template:

<select [(ngModel)]="selectedDepartment">
   <option value="-1">All</option>
   <option value="{{d.Id}}" *ngFor="let d of departments">{{d.Name}}</option>
 </select>
 <div class="card"  *ngFor="let emp of (employees | filter: filterFunc)">

2条回答
可以哭但决不认输i
2楼-- · 2019-05-21 20:00

I think the easiest way is to pass the selected value

 <div class="card"  *ngFor="let emp of (employees | filter: filterFunc:selectedDepartment)">

This way the pipe should be executed every time selectedDepartment changes.

查看更多
Emotional °昔
3楼-- · 2019-05-21 20:21

It's not a good idea to use a pipe for filtering. See the link here: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

Rather, add code in your component to perform your filtering.

Here is an example:

import { Component, OnInit } from '@angular/core';

import { IProduct } from './product';
import { ProductService } from './product.service';

@Component({
    templateUrl: './product-list.component.html'
})
export class ProductListComponent implements OnInit {

    _listFilter: string;
    get listFilter(): string {
        return this._listFilter;
    }
    set listFilter(value: string) {
        this._listFilter = value;
        this.filteredProducts = this.listFilter ? this.performFilter(this.listFilter) : this.products;
    }

    filteredProducts: IProduct[];
    products: IProduct[] = [];

    constructor(private _productService: ProductService) {

    }

    performFilter(filterBy: string): IProduct[] {
        filterBy = filterBy.toLocaleLowerCase();
        return this.products.filter((product: IProduct) =>
              product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1);
    }

    ngOnInit(): void {
        this._productService.getProducts()
                .subscribe(products => {
                    this.products = products;
                    this.filteredProducts = this.products;
                },
                    error => this.errorMessage = <any>error);
    }
}
查看更多
登录 后发表回答