ng-select: What is the difference between using ng-option and ng-template?

2.8k views Asked by At

So I have an array with over 45,000 items and i want to make an ng-select component. I tried displaying the options using ng-option and *ngFor but the component got really slow to load. However, when I used ng-template and [items] property on ng-select, it loaded really fast. Does anyone know why is this happening? Why is ng-template faster than ngFor?

With ng-option:

<ng-select [multiple]="false" [(ngModel)]="selected" [virtualScroll]="true" [items]="list">
  <ng-option *ngFor="let item of list" [value]="item">{{item}}</ng-option>
</ng-select>

With ng-template:

<ng-select [multiple]="false" [(ngModel)]="selected" [virtualScroll]="true" [items]="list">
  <ng-template ng-option-tmp let-item="item">
    {{item}}
  </ng-template>
</ng-select>
2

There are 2 answers

0
Brian Davis On

Virtual scrollport only iterates/renders the items needed at the time on the screen, whereas the for loop has to iterate over the whole list.

0
THE LIFE-TIME LEARNER On

the ng-template approach with [items] is more performant for rendering large datasets because it leverages virtual scrolling to optimize DOM rendering and memory usage, while the ng-option with *ngFor approach creates a DOM element for each item, which can lead to slower performance for large datasets.