【问题标题】:Using a pipe filter, to make it work on several conditions使用管道过滤器,使其在多种条件下工作
【发布时间】:2017-08-07 09:04:52
【问题描述】:

我有一个管道过滤器,它通过name 过滤我的客户列表。我需要添加另一个过滤器,以便客户端可以通过account_number过滤器管道过滤:

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
  name: 'filter',
  pure: false
})

export class FilterPipe implements PipeTransform {

  transform(items: any[], term): any {
    return term ? items.filter(item => item.name.toLowerCase().indexOf(term.toLowerCase()) != -1) : items;
  }

}

在我看来,我是这样绑定过滤器的:

<input type="text" class="form-control" placeholder="Name" name="term" [(ngModel)]="term">
<input type="number" class="form-control" placeholder="Account number"> <!--Here I want to make another ngModel-->

<table>
  <tr *ngFor="let client of clients | filter: term | sortBy: 'id'; let i = index"
    <td>{{client.name}}</td>
    <td>{{client.account_number}}</td>
  </tr>
</table>

那么,我需要创建另一个pipe 以按不同的属性进行过滤,还是可以在单个pipe 中完成?另外,如果它将是两个不同的管道,我应该如何将它包含在视图中的过滤器中?谢谢。

【问题讨论】:

    标签: angular filter pipes-filters


    【解决方案1】:

    你可以用单管试试这个

     transform(values: any[], filter: string): any {
        if (!values || !values.length) return [];
        if (!filter) return values;
    
        filter = filter.toUpperCase();
    
        if (filter && Array.isArray(values)) {
          const keys = Object.keys(values[0]);
          return values.filter(v => v && keys.some(k => v[k].toUpperCase().indexOf(filter) >= 0));
        }
      }
    

    【讨论】:

    • 很遗憾,我收到一个错误:ERROR TypeError: v[k].toUpperCase is not a function
    • 无论我在输入中输入什么,无论是字符串还是数字,我都会得到相同的错误。
    • 可以发布你的数组的样本数据
    • 数组看起来像:[{name: "Alex", account_number: 123}, {name: "Bob", account_number: 456}]等等。
    猜你喜欢
    • 2013-08-11
    • 2019-06-22
    • 2021-12-11
    • 2018-06-16
    • 2019-06-01
    • 2012-05-12
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    相关资源
    最近更新 更多