Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 spinner for ngFor

Tags:

angular

I have a ngFor with lots of elements being rendered and I want to show a spinner while the items are not only loaded but also rendered.

I know how I can display the spinner when loading items from the server (i.e. observables), but that only takes a little time in my case. I can see that majority of the time is spent by browser rendering all the ngFor elements and I dont know how to make sure that spinner is still displayed for this process. I tried ngAfterViewChecked lifecycle hook but thats also triggered before ngFor finishes.

So I wonder is there any way to hook into this process? Alternatively can we force Angular2/browser to display ngFor items incrementally? I.e. show the items as they are being rendered rather show all of them at once after creating templates.

I am using Angular 2.0.0. Any help appreciated.

like image 293
Zyga Avatar asked Nov 09 '22 02:11

Zyga


1 Answers

I'm really, really late to the party, here. Just stumbled on this old question when searching for something else.

The problem lies (well, was) probably in the absence of a trackBy. This is a parameter often overlooked, but crucial for having good performing ngFors.

The trackBy is used to extract a unique identifier from each item in the enumerable sequence passed to ngFor:

<!-- trackById is a method in the component -->
<div *ngFor="let item of items; trackBy: trackById"></div>
// the signature of a trackBy method is fixed and as follows
trackById(index: number, item: any): any {
  // you can track by index, by item, by a property. In this sample we track the
  // items via an 'id' property
  return item.id;
}

In absence of a trackBy function, every single change detection triggered will destroy and recreate the whole list. So, if you have many observable triggering almost simultaneously, the whole ngFor will be recreated once for every single observable triggering.
Having trackBy set up, at every change detection the ngFor directive will not destroy and recreate everything, but it will only update the items changed, remove what has to be removed and insert the new items.

A nice article describing some use cases: https://netbasal.com/angular-2-improve-performance-with-trackby-cc147b5104e5

The API reference documentation: https://angular.io/api/common/NgForOf

like image 56
A. Chiesa Avatar answered Nov 15 '22 06:11

A. Chiesa