angular2 ngfor only if index is less than certain number
Asked Answered
S

2

5

I'm using an ngfor to display a varying amount of items. I want to limit the amount of items it can display to 5 so I use:

<li  *ngFor="let item of items; let i = index;">
     <div *ngIf="i < 4">
       //more stuff ...
     </div>
</li>

But what this does it that it seems to be rendering the space for items over index = 4.

If I try:

<li  *ngFor="let item of items; let i = index;" *ngIf="i < 4"> //Notice ngIF

Nothing is displayed.

Any ideas?

Stelly answered 2/9, 2016 at 0:33 Comment(0)
S
11

You can do it that way:

<li *ngFor="let item of items | slice:0:5; let i = index;">
  <div>
    //more stuff ... 
  </div>
</li>

Maybe that's an option that works for you.

Soothe answered 2/9, 2016 at 1:18 Comment(2)
whats the function of slice here ,could you explain bit more ?Peradventure
slice creates a new array with a subset of the elements in 'items' (in that case with the first 5 elements of 'items'). So the 'ngFor' will only see that temporary array with 5 elements. See also the documentation of SlicePipeSoothe
C
1

You can use ng-template

<ng-template ngFor let-item [ngForOf]="items"  let-i="index" >
        <div *ngIf=" i < 4">
            {{item}}
        </div>
</ng-template>
Calctufa answered 20/12, 2017 at 10:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.