CommonSenseCode
CommonSenseCode

Reputation: 25399

angular2 ngfor only if index is less than certain number

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?

Upvotes: 5

Views: 9318

Answers (2)

LintonB
LintonB

Reputation: 540

You can use ng-template

<ng-template ngFor let-item [ngForOf]="items"  let-i="index" >
        <div *ngIf=" i < 4">
            {{item}}
        </div>
</ng-template>

Upvotes: 1

JRoppert
JRoppert

Reputation: 5952

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.

Upvotes: 11

Related Questions