如何获得在 angular2 中设置的过滤(管道)的大小 [英] How to get the size of a filtered (piped) set in angular2

查看:9
本文介绍了如何获得在 angular2 中设置的过滤(管道)的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了自己的过滤器管道,因为它在 angular2 中消失了:

import {Pipe, PipeTransform} from 'angular2/core';@管道({名称:'我的过滤器'})导出类 MyFilter 实现 PipeTransform {变换(客户数据:数组<对象>,参数:任何[]){如果(客户数据 == 未定义){返回;}var re = new RegExp(args[0]);return customerData.filter((item) => re.test(item.customerId));}}

并在我的模板中使用它:

...</tr>

现在我想看看管道返回了多少匹配项.所以本质上是返回数组的大小.

在 angular 1.x 中,我们可以像这样将返回的集合分配给模板中的变量:

但是我们不能再在 angular2 的模板中分配变量了.

那么如何在不调用过滤器两次的情况下获得过滤集的大小?

解决方案

original

AFAIK 目前无法直接执行此操作.一个技巧是向内容添加模板变量并使用 ViewChildren(...) 查询来获取创建的项目并对其进行计数.

...</tr><div>计数:{{filteredItems?.length}}</div>

@ViewChildren('someVar') 过滤项;

另一种方法是将计数器变量的引用传递给管道,如 https 所示://plnkr.co/edit/Eqjyt4qdnXezyFvCcGAL?p=preview

更新(Angular >=4.0.0)

由于 Angular 4 *ngFor 支持 as

您可以在模板中使用(在添加了 *ngFor 的元素内),如

 

{{result?.length}}

I wrote my own filter pipe as it disappeared in angular2:

import {Pipe, PipeTransform} from 'angular2/core';

@Pipe({
  name: 'myFilter'
})
export class MyFilter implements PipeTransform {
  transform(customerData: Array<Object>, args: any[]) {
    if (customerData == undefined) {
      return;
    }
    var re = new RegExp(args[0]);
    return customerData.filter((item) => re.test(item.customerId));
  }
}

And use it in my template:

<tr *ngFor="#singleCustomerData of customerData | myFilter:searchTerm">
  ...
</tr>

Now I'd like to see how many matches the pipe returns. So essentially the size of the returned array.

In angular 1.x we were able so assign the returned set to a variable in a template like so:

<div ng-repeat="person in filtered = (data | filter: query)">
</div>

But we can no longer assign variables in templates in angular2.

So how do I get the size of the filtered set without calling the filter twice?

解决方案

original

AFAIK there is currently no way to do this directly. A hack would be to add a template variable to the content and use a ViewChildren(...) query to get the created items and count them.

<tr *ngFor="let singleCustomerData of customerData | myFilter:searchTerm" #someVar>
  ...
</tr>
<div>count: {{filteredItems?.length}}</div>

@ViewChildren('someVar') filteredItems;

An alternative approach would be to pass a reference to a counter variable to the pipe like shown in https://plnkr.co/edit/Eqjyt4qdnXezyFvCcGAL?p=preview

update (Angular >=4.0.0)

Since Angular 4 *ngFor supports as

<tr *ngFor="let singleCustomerData of customerData | myFilter:searchTerm as result">

which you can use in the template (inside the element that *ngFor is added to) like

  <div>{{result?.length}}</div>

这篇关于如何获得在 angular2 中设置的过滤(管道)的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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