1

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?

3
  • You can splice the users based on index ``` <div *ngFor="let user of users.splice(0, index); let i = index" [attr.data-index]="i"> {{user?.UserName}}</div> ``` Commented Apr 23, 2020 at 13:07
  • splice does just remove the users in the array right? Commented Apr 23, 2020 at 13:14
  • yes, in that case you can use slice Commented Apr 23, 2020 at 13:19

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.