Ivan Bespalov
Ivan Bespalov

Reputation: 147

How do I get a number of items in a filtered list?

So, I have a filtering pipe and using it to filter a list of cities to show only those that include a search term.

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

    @Pipe({ name: 'filter' })
    export class FilterPipe implements PipeTransform{
        transform(value: any, arg: string) {
            var searchTerm = arg ? arg : '';
            searchTerm = searchTerm.toUpperCase();
            if (value == null) return null;
            return value.filter(el => el.City.toUpperCase().indexOf(searchTerm) !== -1);
        }
    }

But the array of cities I have has 5000 items in it, so I use a slicing pipe to show only five of them.

<form [formGroup]="form">
  <input formControlName="search" type="text">
  <div>
    <li 
    *ngFor="let city of cities | filter:searchTerm | slice:0:5"
    (click)="PasteCity(city.City)">
      {{ city.City }}
    </li>
  </div>
</form>

But there lies a problem. I need to show to the user, how many cities were found, e.g. "5 0f 631 cities are shown". As far as I tried, ViewChildren and indexing the last element of *ngFor methods only got me the number of cities shown, not found by filter... But whilst trying to use ViewChildren I got an error and quickly scraped this idea

Upvotes: 1

Views: 1894

Answers (1)

bergben
bergben

Reputation: 1415

Did you try

(cities | filter:searchTerm).length 

?

Upvotes: 5

Related Questions