如何为 Angular 2 ngb-pagination 实现 Bootstrap 4

How to implement Bootstrap 4 for Angular 2 ngb-pagination

我有一个带有 componentAngular2 应用程序,而我有一个 table。 Table 是通过 *ngFor 指令生成的。 table 的每一行都是一个包含 9 个字段的对象,该对象是在组件初始化时从后端加载的。 在应用程序中,我正在尝试将 ng-bootstrap 用于 angular 模块。 ng-boorstrap 特别是我正在尝试实现 pagination 组件。

有人可以解释一下如何放置代码以便呈现例如每页只有10行? 或者给我一个实现完成的参考。

我所做的是:

好的。我在 github 中找到了一个很棒的解决方案。 看看这个。 https://github.com/michaelbromley/ng2-pagination

这是我的工作解决方案。 API 对于 ngb-分页:https://ng-bootstrap.github.io/#/components/pagination

    ...
</table>
<ngb-pagination [collectionSize]="totalItems" [pageSize]="itemsPerPage" [(page)]="page" [maxSize]="7" [rotate]="true" (pageChange)="loadPage($event)"></ngb-pagination>

在您的组件中,您需要类似的东西。不要忘记在构造函数中设置变量:

  itemsPerPage: number;
  totalItems: any;
  page: any;
  previousPage: any;

  ...
  loadPage(page: number) {
    if (page !== this.previousPage) {
      this.previousPage = page;
      this.loadData();
    }
  }
  ...

  loadData() {
    this.dataService.query({
      page: this.page - 1,
      size: this.itemsPerPage,
    }).subscribe(
      (res: Response) => this.onSuccess(res.json(), res.headers),
      (res: Response) => this.onError(res.json())
      )
  }

我一直在寻找同一个问题的答案,但似乎没有人 post 有明确的答案。

这是我的解决方案:

ngbPagination with ngFor in Angular 7

export class HomeComponent implements OnInit {


currentPage = 1;
itemsPerPage = 5;
pageSize: number;

constructor() { }

  public onPageChange(pageNum: number): void {
    this.pageSize = this.itemsPerPage*(pageNum - 1);
  }
  
  public changePagesize(num: number): void {
  this.itemsPerPage = this.pageSize + num;
}

}
<div class="container-fluid">
    <div class="col-6 input-group">
        <div class="col-5 input-group-addon">
            <ngb-pagination [collectionSize]="users.length" #numPages [pageSize]="itemsPerPage" [(page)]="currentPage" (pageChange)="onPageChange(currentPage)"></ngb-pagination>
        </div>
        <div class="col-1 input-group-addon">
            <input class="input-sm text-center" type="number" [min]="10" [max]="users.length" step="1" [(ngModel)]="itemsPerPage" (onClick)="changePagesize(pageSize)">
        </div>
    </div>
    <ul *ngIf="users">
        <li *ngFor="let user of users | slice: pageSize | slice: 0:itemsPerPage">
            <img [src]="user.avatar" alt="{{ user.avatar }}">
            <p>{{ user.id }}. {{ user.first_name }} {{ user.last_name }}</p>
        </li>
    </ul>
    <pre><span class="float-md-left">Page: {{ currentPage }} / {{numPages.pageCount}}</span><span class="float-md-right">Found items: {{ itemsPerPage }} / {{ users.length }}</span></pre>
</div>

此方案同样适用Angular6.其他版本我没有测试过

有关详细信息,请查看 documentation。不幸的是...它缺少有关 ngFor 迭代的重要信息。

我遇到的另一个问题是如何设置页数。我决定为那些有同样问题的人添加我的完整解决方案。我找到了这个答案 here. Take note of the identifier #numPages above. Here is a live demo on stackblitz