Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - ngFor display last 3 items in array

Tags:

angular

ngfor

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

like image 448
Mike Trinh Avatar asked Nov 28 '22 00:11

Mike Trinh


2 Answers

<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.

like image 86
Günter Zöchbauer Avatar answered Dec 22 '22 10:12

Günter Zöchbauer


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.

like image 37
jnthnjns Avatar answered Dec 22 '22 11:12

jnthnjns