管道转换后在 ngFor 中获取数组的长度

Get length of array in ngFor after pipes transformation

我有以下模板:

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

很遗憾,ngFor 中不存在长度。我怎样才能解决这个问题,让我的 ngFor 中有可用的长度?

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

另见 https://angular.io/api/common/NgForOf

另一种解决方案如下

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

Plunker Example

另见

好吧,这在 Angular 文档中没有很好的记录,您可以在 Angular 的源代码下找到 -

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

*ngFor 接受计数参数。

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

所以我们可以得到这样的计数 -

<div *ngFor="let item of items | pipe; let l = count">
<div>{{count}}</div>
</div>

@Günter Zöchbauer {{(myArray | customPipe)?.length}} - 按预期工作

这听起来可能很脏(确实如此)

但是 const count = document.getElementbyId('id-of-wrapper').childElementCount; 就可以了。

需要在某些事情发生变化时调用此函数。

优点

  • 不需要重新计算管道
  • 有效
  • 循环外可用计数

缺点

  • 脏(有点)
  • 不正确的angular方式
  • 依赖于dom