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

时间:2017-08-16 20:30:57

标签: angular angular-pipe

我有一份员工名单,想要使用预定义的部门过滤器下拉

我试图制作一个过滤管并将一个函数作为一个arg传递,它只在第一次渲染时起作用,但我想在每次用户更改选择时调用管道

管:

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

2 个答案:

答案 0 :(得分:3)

我认为最简单的方法是传递选定的值

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

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

答案 1 :(得分:2)

使用管道进行过滤并不是一个好主意。请参阅此处的链接: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);
    }
}