在将函数作为 arg Pipe angular2 传递时调用管道

invoke pipe when passing function as arg Pipe angular2

我有一个员工列表,想要使用预定义的部门过滤器进行下拉列表

我正在尝试创建一个过滤器管道并将一个函数作为参数传递,它只在第一次渲染时起作用,但我想在每次用户更改选择时调用该管道

管道:

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));
    }
   }

分量:

     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;
     } 
  }

模板:

<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)">

使用管道进行过滤不是一个好主意。请参阅此处的 link:https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

相反,在您的组件中添加代码来执行过滤。

这是一个例子:

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);
    }
}

我觉得最简单的方法就是传选值

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

这样,每次 selectedDepartment 更改时都应执行管道。