Get length of array in ngFor after pipes transform

2019-04-06 05:08发布

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?

3条回答
手持菜刀,她持情操
2楼-- · 2019-04-06 05:49

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>
查看更多
叼着烟拽天下
3楼-- · 2019-04-06 05:54

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

查看更多
Melony?
4楼-- · 2019-04-06 06:00
<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

查看更多
登录 后发表回答