Angular 2 - ngFor display last 3 items in array

前端 未结 4 618
情书的邮戳
情书的邮戳 2021-02-06 15:44

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

got in my html

          
  • 相关标签:
    4条回答
    • 2021-02-06 16:22

      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>
      
      0 讨论(0)
    • 2021-02-06 16:23

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

      0 讨论(0)
    • 2021-02-06 16:36

      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.

      0 讨论(0)
    • 2021-02-06 16:42
      <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.

      0 讨论(0)
    提交回复
    热议问题