neric neric - 1 month ago 20
TypeScript Question

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';

name: 'myFilter'
export class MyFilter implements PipeTransform {
transform(customerData: Array<Object>, args: any[]) {
if (customerData == undefined) {
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">

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)">

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?


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="#singleCustomerData of customerData | myFilter:searchTerm" #someVar>
<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