直接在* ngFor中使用切片还是通过管道使用切片之间有区别? [英] Is there a difference between using slice in *ngFor directly or by pipe?

查看:57
本文介绍了直接在* ngFor中使用切片还是通过管道使用切片之间有区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有条件地( more = true/false )使用切片管道显示列表或完整列表的3个元素

 < div class ="table">< div * ngFor =让list | slice:0的项目:(更多?未定义:3)" class ="row">{{item.id}} {{item.name}}< div></div> 

 <!-替代形式->< div class ="table">< div * ngFor =让(更多?列表:list | slice:0:3)的项目成为现实" class =" row>{{item.id}} {{item.name}}< div></div>  

但是我可以直接使用 slice (无管道)

 < div class ="table">< div * ngFor =使list.slice(0,more?undefined:3)的项保持不变.{{item.id}} {{item.name}}< div></div> 

 <!-替代形式->< div class ="table">< div * ngFor =让(more?list:list.slice(0,3))的项目成为"class =" row>{{item.id}} {{item.name}}< div></div>  

两种解决方案均有效.它们之间在性能上有区别吗?

更新

有关此案例的更多信息此处

解决方案

主要区别在于, .slice()是一个函数调用,可以在更改时执行当 SlicePipe 是纯净的时,将触发检测.这意味着,仅当传递的参数更改时才执行.

因此,我建议避免在模板内部调用方法(或使用getter),因为应用程序越大,它们可能会对性能产生巨大影响.这是关于该主题的相关文章有关纯管道的角度文档.

第一部分是不正确的,正如 Alex K 所述,因为 SlicePipe 不纯.因此,不会有明显的差异.

尽管在模板中使用函数或getter是不好的做法(只要您不遵循 OnPush 更改检测策略),更好的方法是将逻辑用于组件控制器内部的数组.

I want to conditionally (more=true/false) show 3 elements of list or full list using slice pipe

<div class="table">
  <div *ngFor="let item of list|slice:0:(more ? undefined : 3 )" class="row">
      {{ item.id }} {{ item.name }}
  <div>
</div>

<!-- alternative form -->

<div class="table">
  <div *ngFor="let item of (more ? list : list|slice:0:3)" class="row">
      {{ item.id }} {{ item.name }}
  <div>
</div>

but I can use slice directly (without pipe)

<div class="table">
  <div *ngFor="let item of list.slice(0,more ? undefined : 3)" class="row">
      {{ item.id }} {{ item.name }}
  <div>
</div>

<!-- alternative form -->

<div class="table">
  <div *ngFor="let item of (more ? list : list.slice(0,3) )" class="row">
      {{ item.id }} {{ item.name }}
  <div>
</div>

Both solutions works. Is there a performance difference between them?

UPDATE

More about this case here

解决方案

The main difference is, that .slice() is a function call that may be be executed when ever the change detection is triggered, while the SlicePipe is pure. This means, it's only executed, when the passed parameters change.

Therefore I'd recommend to avoid calling methods (or using getters) inside of templates, since they may have a massive performance impact the larger the app becomes. Here's an article on that topic and the angular docs about pure pipes.

The first part is not true, as a Alex K mentioned, since the SlicePipe is impure. Thus, there won't be a noticeable difference.

Though it's bad practice to use functions or getters inside of templates (as long as you're not following the OnPush change detection strategy), the better way would be to put the logic for slicing the array inside the components controller.

这篇关于直接在* ngFor中使用切片还是通过管道使用切片之间有区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆