Angular 2 - ngFor display last 3 items in array

余生长醉 提交于 2020-12-28 22:56:10

问题


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


回答1:


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




回答2:


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.




回答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>



回答4:


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)">



来源:https://stackoverflow.com/questions/38975981/angular-2-ngfor-display-last-3-items-in-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!