4

got an array with many projects and i want to display the last 3 projects.

got in my html

          <li *ngFor="let project of projects;">
            <h2>{{ project.name }}</h2>
            <p>{{ project.meta_desciption }}</p>
          </li>

it s displaying all the project now (over 20). how can i display only the last 3? I think i need to use "last" somewere in my code, but can't figure it out https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html

4 Answers 4

16
<li *ngFor="let project of (projects | slice:projects.length - 4);">

You might need some additional null check for projects or ensure that it is always an array.

Sign up to request clarification or add additional context in comments.

1 Comment

You don't need the parenthesis and also don't need projects.length. You can just use: <li *ngFor="let project of projects | slice:-4">
4

Gunter's answer above didn't work in my case. I was able to accomplish the same thing but slightly different:

<ng-container *ngFor="let project of projects; let i = index">
    <li *ngIf="i > projects.length - 4">
        <h2>{{ project.name }}</h2>
        <p>{{ project.meta_desciption }}</p>
    </li>
</ng-container>

If the index of the loop is greater then the length of the array minus 4. So if the length is less then 3 it prints all, if it is 3 or greater it just prints the last 3 in whatever order they come in.

1 Comment

Actually. This answer would make a big problem if the <ng-container> has any style by it's own. the page would still render the ng-container with it's style. That's why angular slice pipe comes in handy
3

As answered by Gunter above, you might also need to check the length of "projects" is greater than 4.

<div *ngIf="projects.length>4">
    <li *ngFor="let project of projects;">
        <h2>{{ project.name }}</h2>
        <p>{{ project.meta_desciption }}</p>
    </li>
</div>

Comments

3

In my case for getting last three project below code work perfect no need to check projects length it work for any length of array.

<li *ngFor="let project of (projects | slice: -3)">

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.