基于Angular2中两个或多个属性值的管道过滤器 [英] Pipe filter based on two or more attributes value in Angular2

查看:161
本文介绍了基于Angular2中两个或多个属性值的管道过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有

 [
   {name: 'aaa', type: 'A'},
   {name: 'aaa', type: 'B'},
   ....
 ]

如何使用ngFor表达式中的管道创建过滤器,类似

How can I create a filter using pipe inside ngFor expression, something like

*ngFor='let obj of array | filter:name[nameValue]:type[typeValue]

在这里, name [nameValue] name是一个属性, nameValue 是它的值.只能同时显示与name属性中的nameValue和type属性中的typeValue相匹配的对象.

Here, name[nameValue] name is a property, nameValue is its value. only show the objects which match the nameValue in name property and typeValue in type property simultaneously.

我想要一个更通用的过滤器,该过滤器可以使用任何 property [propertyValue] 并可以相应地过滤输出.

I Want a more generalized filter which takes any property[propertyValue] and can filter output accordingly.

推荐答案

这是一种实现方法.只需给过滤器管道一个包含您要使用其过滤值的字段数组即可.

This is a way you could do it. Just give the filter pipe an array of the fields with the values you want to filter it with.

管道:

@Pipe({
    name: 'filter',
    pure: false
})
export class FilterPipe implements PipeTransform {

    transform(values: Array<any>, args:any[]):any {
        return values.filter((value) => {
            for (let i = 0; i < args.length; i++) {
                if (value[args[i][0]] != args[i][1]) {
                    return false;
                }
            }
            return true;
        });
    }
}

模板中的代码:

  <h3>Only Type A:</h3>
  <div *ngFor="let elm of arr | filter:[['type', 'A']]">
    <span>Name: {{elm.name}}</span> | <span>Type: {{elm.type}}</span>
  </div>

  <h3>Name bbb and Type B:</h3>
  <div *ngFor="let elm of arr | filter:[['type', 'B'], ['name', 'bbb']]">
    <span>Name: {{elm.name}}</span> | <span>Type: {{elm.type}}</span>
  </div>


柱塞作为工作示例

这篇关于基于Angular2中两个或多个属性值的管道过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆