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
<div class="card" *ngFor="let emp of (employees | filter: filterFunc:selectedDepartment)">
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:
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);
}
}