16

I have the following template:

<div *ngFor="let item of myArray | customPipe1 | customPipe2; let l = length">
  Here is the length of my ngFor : {{l}}
</div>

Unfortunately length doesn't exist in ngFor. How can I work around this issue to have the length available inside my ngFor?

Jota.Toledo
  • 27,293
  • 11
  • 59
  • 73
Scipion
  • 11,449
  • 19
  • 74
  • 139

5 Answers5

29

Another solution could be the following

<div *ngFor="let item of myArray | customPipe1 | customPipe2; let l = count">
  Here is the length of my ngFor : {{l}}
</div>

Plunker Example

See also

yurzui
  • 205,937
  • 32
  • 433
  • 399
16
<div *ngFor="let item of myArray | customPipe1 | customPipe2 as result">
  Here is the length of my ngFor : {{result.length}}
</div>

See also https://angular.io/api/common/NgForOf

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
1

Well, this is not well documented in the Angular doc, you can find under source code of Angular at -

https://github.com/angular/angular/blob/master/packages/common/src/directives/ng_for_of.ts

*ngFor accepts count params.

constructor(public $implicit: T, public ngForOf: NgIterable<T>, public index: number,public count: number) {
}

So we can get the count like -

<div *ngFor="let item of items | pipe; let l = count">
<div>{{count}}</div>
</div>
Kanchan
  • 1,609
  • 3
  • 22
  • 37
0

@Günter Zöchbauer {{(myArray | customPipe)?.length}} - Working as Expected

Praburam S
  • 155
  • 2
  • 9
0

This might sound dirty (it is)

But const count = document.getElementbyId('id-of-wrapper').childElementCount; will do the trick.

Need to call this function when some thing changes.

Pros

  • Not require re calculation of pipe
  • Works
  • count available outside of loop

Cons

  • dirty (a bit)
  • not proper angular way
  • dependency on dom
Akshay
  • 3,558
  • 4
  • 43
  • 77