How can I limit ngFor repeat to some number of items in Angular?

My Code:

<li *ngFor="let item of list; let i=index" class="dropdown-item" (click)="onClick(item)">
  <template [ngIf]="i<11">{{item.text}}</template>
</li>

I am trying to have only 10 list elements display at any point. As suggested in the answer here, I used ngIf but this results in empty list items (beyond 10) showing up on the page.


Solution 1:

This seems simpler to me

<li *ngFor="let item of list | slice:0:10; let i=index" class="dropdown-item" (click)="onClick(item)">{{item.text}}</li>

Closer to your approach

<ng-container *ngFor="let item of list" let-i="index">
  <li class="dropdown-item" (click)="onClick(item)" *ngIf="i<11">{{item.text}}</li>
</ng-container>

Solution 2:

You can directly apply slice() to the variable. StackBlitz Demo

<li *ngFor="let item of list.slice(0, 10);">
   {{item.text}}
</li>

Solution 3:

For example, lets say we want to display only the first 10 items of an array, we could do this using the SlicePipe like so:

<ul>
     <li *ngFor="let item of items | slice:0:10">
      {{ item }}
     </li>
</ul>