peter 73
peter 73

Reputation: 85

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?

Upvotes: 3

Views: 1956

Answers (2)

Rohit Sengar
Rohit Sengar

Reputation: 157

**You could build a solution without Rxjs ** consider you have array of items

  • use the ngFor directive inside the ngIf directive then you can easily get the count of the filtered array
<ng-container *ngIf= " (items | searchFile: 'searchItem') as filteredItems">
  {{filteredItems.length}}
  <ng-container *ngFor="let item of filteredItems">
     {{items}}
  </ng-container>
</ng-container>

Upvotes: 0

Basavaraj Bhusani
Basavaraj Bhusani

Reputation: 5673

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.

Upvotes: 4

Related Questions