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)">
I think the easiest way is to pass the selected value
This way the pipe should be executed every time
selectedDepartment
changes.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: