Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular efficiently using trackBy with ngFor

In Angular, is the trackBy function necessary for *ngFor? I saw a few articles here, here, here, and here that say using trackBy will improve performance and has better memory management. But I was wondering if trackBy is such an improvement, then why isn't it default behavior? Is it default behavior and everything I am looking at is out of date?

If it isn't default behavior, my project has about 90 *ngFor in 90 components and I was wondering if there was a way to use the trackBy where I am not including the following function 90 times. I also want to avoid adding a service and importing that 90 times.

HTML

<mat-option *ngFor="let l of list; trackBy: trackByFn" [value]="l.id">
   {{l.name}}
</mat-option>

TS

trackByFn(index, item) {
    return index
}
like image 965
rhavelka Avatar asked Apr 17 '18 15:04

rhavelka


2 Answers

An optimized solution:

Problem: Rendering views is an expensive task of O(n) list


Solution: we are typically rolling the viewport on scrolls which involves removing and adding with the same number of views. rather than deleting the views and creating them all again, we recycle them. So we detach the views, remove the context, and cache them so we can attach them and re-context them on the add cycle. Therefore saving a considerable number of script/render cycles. (In android it's called recycler view)

here is are few angular library that does that exactly as mentioned, better performance than trackBy function

  1. https://material.angular.io/cdk/scrolling/overview

  2. https://github.com/rintoj/ngx-virtual-scroller(this lib is no longer maintained and does not work with latest angular versions but if you still wanted to use copy-paste to your source and import in your module)

  3. https://github.com/anagram4wander/ng-vfor-lib

like image 143
Divek John Avatar answered Sep 21 '22 13:09

Divek John


I have created an animation which shows how both ngFor and ngFor with trackBy manipulates DOM side by side. enter image description here

read article here: https://link.medium.com/ckBRk9wrinb

like image 23
Yousaf Avatar answered Sep 25 '22 13:09

Yousaf