Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slow rendering of template using angular2 *ngFor

Tags:

angular

How can I increase the performance when rendering a template multiple times using ngFor? I have a situation where I need to show the same template based upon the count. I am doing this using *ngFor.

The template loads correctly but I am worried about the performance. Because I need to repeatedly show the same content for a few thousand times, then the performance will be slow after the template is loaded. I have made a plunker demo here http://plnkr.co/edit/qTj4SVRnFD6N15PZ1GWC?p=preview - please increase the count of formgroups in formarray with a difference of 1000 then the system will be slow or breaks down.

This is how I create the formarray:

       for(var i=0;i<100;i++){
  let dummyFormGroup=this.fb.group({
    'name':[''],
    'place':['']
  })
  this.dummyFormArray.push(dummyFormGroup);
}

And I render the controls in formarray using ngFor like this:

  <div *ngFor="let formgroup of dummyFormArray.controls"   style="display:flex;flex-direction:row">
<p>
  <label>Name:</label>
  <input type="text" [formControl]="formgroup.controls['name']" />
</p>
<p>
<label>Place:</label>
<input type="text" [formControl]="formgroup.controls['place']" />
</p>

How can I increase the performance once the template is loaded? Because I am OK with waiting for the template to load if it needs to render thousands of records. But once the template is ready I want the system to be fast in this case using *ngFor.

like image 843
abhilash reddy Avatar asked Oct 01 '16 12:10

abhilash reddy


2 Answers

By default angular checks for change detection in every component in the tree.

So for example if you bind key up, to your input components, things are going to be messy pretty fast.

More on change detection here : https://stackoverflow.com/a/39802466/4299560

like image 83
Ced Avatar answered Oct 14 '22 14:10

Ced


You could also improve the performance by only rendering the visible templates. Let's say that you start rendering 10 templates, and when you start scrolling (to the bottom of the page), you render more. The web-browser takes some time to render all the DOM-elements. Rendering "just-on-time" is better than rendering "all-at-once". All the data will still be in memory, making sure that sorting, or searching for specific templates may be possible.

like image 1
John Avatar answered Oct 14 '22 13:10

John