3
votes

I am a novice in angular and I have a silly problem, how can I show actual number of items outside *ngFor loop ?

I'm using filter and pagination pipes like this

*ngFor="let item of items| filterBy: ['name','category']: queryString | paginate: config; let i = index; let c = count"

I know that there is a variable 'count' but of course it is available only in that loop, how can I get this variable in component, do I need to create new component, put it in that loop and pass 'count' through directives or there is some simpler, cleaner way?

1
get its length and save it in a variable and use it? - Ahmad Alfy
You should avoid using filter pipes. Filter in the controller instead and save it to a variable which you display. The you can just display the length of that array. - Ingo Bürk
You have a problem because you're using pipes to manipulate data. Don't do it. Business logic belongs to your code. - Lazar Ljubenović
hm.. but pipes are cool :) ok. moving filtering to component is probably good solution, thanks - peter 73
I agree with the suggestions of not using filtering pipe. There is a mention of it also in the docs: angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe :) - AT82

1 Answers

4
votes

Using RxJS Subject worked for me.

In the component create a variable to hold the count i.e. filterCount and create a RxJS Subject for type number. Have subscription to unsubscribe the Observable on OnDestroy

filterCount = 0;
filteredCountSubject = new Subject<number>();
subscription: Subscription;

subscribe to the filteredCountSubject on OnInit lifecycle hook.

ngOnInit(): void {
    this.subscription = this.filteredCountSubject.subscribe((count) => {
        this.filterCount = count;
    });
}

In Template, You can display the count using filterCount wherever you want in the template. using

<div>{{filterCount}}</div>

And send the filteredCountSubject as parameter to the filterBy pipe.

<div *ngFor="let item of items| filterBy: ['name','category']: queryString: filteredCountSubject  | paginate: config; let i = index; let c = count"></div>

In transform method of the filterBy pipe, Do filteredCountSubject.next with the count of filtered array. i.e.

transform(items: Array<any>, filterConfig: FilterCofig): Array<any> {
    // Arguments sent from HTML.
    const args = arguments;

    // CODE TO FILTER ITEMS BASED ON PARAMETERS.

    // Get the "filterredCountSubj" from arguments.
    // Remember that the argument index of "filteredCountSubject" is 3. As "items" is first argument.
    const filterredCountSubj = args[3];
    if (filterredCountSubj) {
        filterredCountSubj.next(items.length);
    }
    return items;
}

Hope it helps.