我有一个员工列表,并希望使用预定义的部门过滤器进行下拉
我试图制作一个过滤器管道并将函数作为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)">
最佳答案
我认为最简单的方法是传递选定的值
<div class="card" *ngFor="let emp of (employees | filter: filterFunc:selectedDepartment)">
这样,每次
selectedDepartment
更改时都应执行管道。关于angular - 将函数传递为arg时调用管道,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45722483/