【问题标题】:Get length of array in ngFor after pipes transformation在管道转换后获取 ngFor 中的数组长度
【发布时间】:2017-11-15 05:13:23
【问题描述】:

我有以下模板:

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

不幸的是,ngFor 中不存在长度。如何解决此问题以在我的 ngFor 中提供可用的长度?

【问题讨论】:

  • 你已经有myArray.length我不明白这个问题
  • 这取决于你想要什么,你能提供更多的上下文吗?您可以在文档中查看 ngFor 提供的内容:angular.io/api/common/NgForOf
  • @echonax 长度可以通过使用管道来改变。例如过滤功能:)
  • @PierreDuc 啊,谢谢,可能是这样。

标签: angular angular2-pipe


【解决方案1】:

另一种解决方案可能如下

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

Plunker Example

另见

【讨论】:

【解决方案2】:
<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

【讨论】:

  • 自 Angular 2 最终版本发布以来,我一直期待它能够正常工作,并且很早就添加了答案:D here,+1 链接
  • 如何获取 ngFor 之外的长度?
  • @Luckylooke {{(myArray | customPipe)?.length}}
  • 感谢@GünterZöchbauer,但我想知道无需多次执行管道的解决方案。比如:&lt;div *ngFor="let item of myArray | heavySearchExecution as result"&gt; Here is the length of my ngFor : {{result.length}} &lt;/div&gt; &lt;div *ngIf="!result.length"&gt; No results, please do something else... &lt;/div&gt;
  • 在代码中进行过滤并将结果数组分配给一个字段,并在绑定中使用该字段。
【解决方案3】:

嗯,这在 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>

【讨论】:

    【解决方案4】:

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

    【讨论】:

      【解决方案5】:

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

      但是const count = document.getElementbyId('id-of-wrapper').childElementCount; 可以解决问题。

      当某些事情发生变化时需要调用这个函数。

      优点

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

      缺点

      • 脏(有点)
      • 角度不正确
      • 对dom的依赖

      【讨论】:

        猜你喜欢
        • 2017-12-10
        • 1970-01-01
        • 1970-01-01
        • 2016-04-23
        • 1970-01-01
        • 2015-08-05
        • 2015-08-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多