Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 858
neric Avatar asked Feb 01 '16 09:02

neric


People also ask

What is difference between filter and pipe in Angular?

In Angular 1, we had filter which helped format, sort or transform how data was displayed in our templates. Filters can be used with a binding expression or a directive. In Angular 2, we have a similar feature but renamed to Pipes. This rename was to better align of what the feature does.

What is .pipe in Angular?

Pipes are simple functions to use in template expressions to accept an input value and return a transformed value. Pipes are useful because you can use them throughout your application, while only declaring each pipe once.

How many pipes are there in Angular?

By using the advantage of chaining, we can use two different pipes for the same property or column.


1 Answers

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

{{ (customerData | myFilter:searchTerm)?.length }} 
like image 130
A. Morel Avatar answered Sep 24 '22 22:09

A. Morel