ZaraZahara
ZaraZahara

Reputation: 55

Angular NgFor iterate through x objects in array

I want to iterate through the first four objects of an array. I want to use ngFor instead of selecting the first four objects like this:

{{ users[*]?.UserName }} 

* being the 0-3

I want to use this:

<div *ngFor="let user of users; let i = index" [attr.data-index]="i"> 
{{user?.UserName}}

This works but displays all users in the array and I only need the first 4 (index 0-3). Is there a way to tell the ngFor something like: i<4?

Upvotes: 1

Views: 293

Answers (2)

Hien Nguyen
Hien Nguyen

Reputation: 18975

You can use pipe slice:0:3 like below

<div *ngFor="let user of users | slice:0:3; let i = index" [attr.data-index]="i">

    {{user?.UserName}}

Demo https://stackblitz.com/edit/angular-hjgubx

Upvotes: 0

Sayooj V R
Sayooj V R

Reputation: 2363

You can try like this. use ngconainter and ng if for limiting the number of users to 4.

<div *ngFor="let user of users; index as i" [attr.data-index]="i"> 
    <ng-container *ngIf="i<4">
       {{user?.UserName}}
    </ng-container>
</div>

Upvotes: 1

Related Questions