Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 *ngFor items count outside the loop

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?

like image 551
peter 73 Avatar asked Feb 18 '26 10:02

peter 73


1 Answers

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.

like image 132
Basavaraj Bhusani Avatar answered Feb 20 '26 00:02

Basavaraj Bhusani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!