How to find the count of items in an ngFor after the pipes have been applied

Viewed 57206

I have an ngFor creating rows in a table that is both filtered and paged.

<tr *ngFor="#d of data.results | filter:filterText | pagination:resultsPerPage:currentPage">

There is another element on the page that displays the number of records displayed. These elements are initially bound to the data.Results' length.

How do I get the length of the data that is displayed after the filter pipe has been applied so that I can display it correctly. None of the provided local variables in ngFor seem to account for this.

9 Answers

Assume your ngFor looks something like:

<div #cardHolder>
    <app-card *ngFor="let card of cards|pipeA:paramX|pipeB:paramY"></app-card>
</div>

Then in your component you may use something like:

 get displayedCards() : number {
    let ch = this.cardHolder.nativeElement;

    // In case cardHolder has not been rendered yet...
    if(!ch)
      return 0;

    return ch.children.length;

  }

Which you may display in your view by simple interpolation

{{displayedCards}}

Advantages include not needing to modify the pipes to return additional data.

  1. What worked for me is:

    • Don't use pipes, few months later you will not be able to tell what they mean nor figure out the weird syntax.

    • Frameworks, here Angular, are ok, but to a certain point, keep the template simple ngFor binding to an array of your data. Going beyond that means you will get tangled in particular framework peculiar syntax and (changing) mechanisms. (this explain why we have this post/question which should not exist in the first place)

    • HTML template is meant for layout keep it as such. All logic, data filtering, etc... should be kept in the code behind in straightforward classes.

  2. Simply make a filter method in your component or service and call it to filter your data.

  3. Expose a .Count prop on your component/service to display your actual filtered data dynamic count (ie. typically .length).
Related