将函数传递为arg时调用管道 [英] invoke pipe when passing function as arg Pipe angular2
本文介绍了将函数传递为arg时调用管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个员工列表,并希望使用预定义的部门过滤器进行下拉
I have a list of emplyees and want to make a drop down with predefined department filter
我正在尝试制作过滤器管道并将函数作为arg传递,它仅在第一次呈现时才起作用,但是我想在用户每次更改选择内容时调用管道
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
管道:
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)">
推荐答案
我认为最简单的方法是传递所选值
I think the easiest way is to pass the selected value
<div class="card" *ngFor="let emp of (employees | filter: filterFunc:selectedDepartment)">
这样,每次selectedDepartment
更改时都应执行管道.
This way the pipe should be executed every time selectedDepartment
changes.
这篇关于将函数传递为arg时调用管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文