Angular2中嵌套列表的分页

问题描述 投票:2回答:2

我有一个嵌套的项目列表,我正在尝试分页,但我发现的大多数Pagination实现似乎不适用于嵌套列表。

app.component.html:

<div *ngFor="let department of myJSON">
    <h2>{{department.title}}</h2>
    <p>{{department.description}}</p>
    <ul class="list">
        <li *ngFor="let person of department.list">
            {{person.name}}
            {{person.phone}}
        </li>
    </ul>
</div>

为了澄清,我在这个页面上只需要一个分页元素,并且所有部门都使用它来为每个10“li”元素分页。如果某个部门为空(因为它在当前显示的页面上没有元素),那么它将收到display:none。

我已经尝试过NgxPaginationModule,但它似乎没有任何支持识别当前ngFor之外的元素。

我发现最接近的是:Pagination of nested objects in angular js,其中他解释了如何从头开始编写自定义Pager,但同样,似乎没有任何方法可以计算显示多少LI,并且每页只显示10个。

任何帮助或方向将不胜感激!

angular pagination nested-loops ngfor
2个回答
2
投票

最后,我找不到任何强制我从头开始构建完整分页的解决方案。

因此,我改为扁平化并重建我的数组,并重新编写app.component.html以删除所有嵌套循环,并使用标准的ngx-pagination。

这是我使用的HTML的最终版本:

app.component.html:

//itemList = current page of items.
//i = index
//person = item on page
//If a person is the first one on the page(index=0) or his department ID
//is different from the previous person's department ID, then print 
//the .deparment-section block.

<ng-template ngFor let-person let-i="index" let-itemList="ngForOf" [ngForOf]="personList | paginate: { itemsPerPage: 10, currentPage: p }">
    <div class="department-section" *ngIf="  person.department.id && (i == 0 || person.department.id != itemList[i-1].department.id)">
        <h2>{{departmentList[person.department.id].name}}</h2>
        <p>{{departmentList[person.department.id].description}}</p>                
    </div>
    <div class="person">
        {{person.name}}
        {{person.phone}}
    </div>
</ng-template>

1
投票

Eliezer,“关键”是向你的部门添加变量“count”和“activePage”。你可以使用一些类似的地图

//supouse you have a an array "departments" that is 
//an object with title,description and list -this last is an array too
this.department=department.map(d=>{
   title:d.title,
   description:d.description,
   count:d.list.length,
   activePage:0,
   list:d.list
});

然后你可以使用拆分只显示十个人

<div *ngFor="let department of myJSON">
    <h2>{{department.title}}</h2>
    <p>{{department.description}}</p>
    <ul class="list">
        <li *ngFor="let person of 
                department.list.slice(department.activePage,10*(department.activePage))">
            {{person.name}}
            {{person.phone}}
        </li>
    </ul>
    <button (click)="department.activePage++">more</button>
    <button (click)="department.activePage--">less</button>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.