I have an ngFor creating rows in a table that is both filtered and paged.
-
I came across the same problem, although @bixelbits 's answer was approved, but I didn't find it ideal, specially for large data.
Instead of returning the original array in each element, I believe it's better just avoid Pipes
for this problem, at least with the current Angular 2 implementation (rc4).
A better solution would be using normal component's function to filter the data, something likes bellow:
// mycomponent.component.ts
filter() {
let arr = this.data.filter(
// just an example
item => item.toLowerCase().includes(
// term is a local variable I get it's from <input>
this.term.toLowerCase()
)
);
this.filteredLength = arr.length;
return arr;
}
Then, in the template:
<ul>
<li *ngFor="let el of filter()">
{{ el | json }}
</li>
</ul>
// mycomponent.component.html
<p > There are {{ filteredLength }} element(s) in this page</p>
Unless you really want to use Pipes
, I would recommend you to avoid them in situations like the above example.
讨论(0)
-
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.
Simply make a filter method in your component or service and call it to filter your data.
- Expose a .Count prop on your component/service to display your actual filtered data dynamic count (ie. typically .length).
讨论(0)
-
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.
讨论(0)
- 热议问题