直接在* ngFor中使用切片还是通过管道使用切片之间有区别?

时间:2019-12-13 21:27:49

标签: angular

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

<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>

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

<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>

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

更新

有关此案件here

的更多信息

2 个答案:

答案 0 :(得分:3)

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

因此,我建议避免在模板内部调用方法(或使用getter),因为应用越大,它们可能会对性能产生巨大影响。这是article on that topicangular docs about pure pipes

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

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

答案 1 :(得分:1)

slicePipeArray.slice()在Angular表达式中的行为不同。

slicePipe不会为undefinednull值触发模板错误,如果值的类型错误,则会引发invalidPipeArgumentError错误。

>

当您通过Array.slice()值调用undefined时,您会加注ERROR TypeError: Cannot read property 'slice' of undefined。如果您用无效的类型呼叫slice(),则会引发ERROR TypeError: value.slice is not a function

例如,您可以使用undefined运算符来抑制?错误; Array?.slice(...),但这要求开发人员记住始终这样做。

以上是一个重要的区别,因为*ngFor接受undefinednull的值是有效的。例如; <div *ngFor="let i of null"></div>不会引发错误。

它们的执行速度相同。 Web浏览器是*ngFor的性能瓶颈,因为插入DOM元素花费的时间要长得多。如果您使用1000个项目的数组,则调用slice()slicePipe()不会有任何可测量的差异,但是您将看到Web浏览器在更新DOM时有多慢。因此,通过对阵列进行更少的更改,您将获得更好的性能。