12

I'm looping through an array which has 6 objects and using ngFor where I want to loop only up to 4 elements .. How Can I do that??

<div class="item active" *ngFor="#data of lengthArray">
 content 
</div>

In LengthArray I have 6 but how to loop up to 4 records only??

and also I want to loop from 4th record to 6th record in another div.. How can I start from 4th record??

Cosmin Ababei
  • 7,003
  • 2
  • 20
  • 34
sudhir
  • 1,387
  • 3
  • 25
  • 43

3 Answers3

28

You can use the slice pipe with a start and end parameter. The start parameter is required and the end parameter is optional.

<div class="item active" *ngFor="#data of lengthArray | slice:start[:end]">
  content 
</div>
muetzerich
  • 5,600
  • 7
  • 37
  • 52
4

You can capture the index and then make it less then 4

<div class="item active" *ngFor="#data of lengthArray;i=index">
    <div *ngIf="i<=4">
        content
    </div>
</div>

I haven't really tested the code but you can find a lot of examples here on stackoverflow, do more researching...

Angular 2: how to apply limit to *ngFor?

More about filters... How to apply filters to *ngFor

Community
  • 1
  • 1
Marko
  • 917
  • 9
  • 14
0

Simple solution:

<tr *ngFor=""let obj of ArrayogObjs;  let i=index">
        <td *ngIf="i<4">
            {{obj.name}}
        </td>
    </tr>
Shashwat Gupta
  • 5,071
  • 41
  • 33