Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

filter - How to get the size of a filtered (piped) set in angular2

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You still must call the filter a second time but you can use it directly like this :

{{ (customerData | myFilter:searchTerm)?.length }}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...