Search code examples
angularangular-pipe

invoke pipe when passing function as arg Pipe angular2


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

Solution

  • 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.