如何使用ngFor向div添加分页功能

时间:2019-03-28 05:31:49

标签: angular pagination angular-material angular7

如何向div添加分页功能。

app.component.html

<div>

 <div *ngFor="let clg of colleges$">
  <h3>{{clg.name}}</h3>
 </div>

 <mat-paginator [length]="100" [pageSize]="10" [pageSizeOptions]="[5, 10, 25, 
 100]"></mat-paginator>

</div>

4 个答案:

答案 0 :(得分:2)

<div>
    <div ngFor="let item of items| slice: (page-1)*pagesize : page*  pagesize; index as i;">
        <div *ngIf="page==1" scope="row">{{i+1}}</div>
        <div scope="row" *ngIf="page>1">{{((page-1)*pagesize)+(i+1)}}</div>
        <div>{{item}}</div>
    </div>
</div>
<ngb-pagination [collectionSize]="totalItems" [(page)]="page" [(pageSize)]="pagesize" [rotate]="true">
</ngb-pagination>

答案 1 :(得分:0)

您应该使用延迟加载来加载数据。

为此,您首先需要在json文件中获取记录的总长度并设置[length]="totalLength"。然后,mat-paginator将基于totalLength自动为您设置页面。然后,您应该加载前10个数据(即0到10)并将其分配给colleges $。我说10是因为它是[pageSize]。如果您的pageSize为5,则加载前5个数据,依此类推。然后,当用户单击页码(例如2)时,您应该调用api,它应该返回下一组数据,即11到20,并将其分配给colleges $。数据将在视图中自动刷新。

最好创建一个API,该API将在您传递2个参数(偏移量和限制)时为您获取数据,偏移量和限制是您所用的页面大小。分页器中有多种方法(功能),它们会在pageSize更改或用户单击页码时触发

答案 2 :(得分:0)

我将使用mat-paginator的(page)获取选定的值,然后根据该值过滤或拼接数组:

HTML代码:

<div *ngFor="let clg of filteredArray">
    <h3>{{clg.name}}</h3>
</div>
<mat-paginator [length]="100" [pageSize]="defaultRecords" [pageSizeOptions]="[5, 10, 25, 100]" (page)="pageEvent = $event; onPaginateChange($event)">
</mat-paginator>

TS代码:

import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator, MatTableDataSource } from '@angular/material';
/**
 * @title Paginator
 */
@Component({
  selector: 'paginator-overview-example',
  templateUrl: 'paginator-overview-example.html',
  styleUrls: ['paginator-overview-example.css'],
})
export class PaginatorOverviewExample implements OnInit {

  colleges: any[] = [{ name: "1" }, { name: "2" }, { name: "3" }, { name: "4" }, { name: "5" }, { name: "6" }, { name: "7" }, { name: "8" }, { name: "9" }, { name: "10" }, { name: "11" }, { name: "12" }, { name: "13" }];

  filteredArray: any[] = []

  defaultRecords: any = 5;

  ngOnInit() {
    this.filteredArray = this.colleges.slice(0, this.defaultRecords);
  }

  onPaginateChange(data) {
    this.filteredArray = this.colleges.slice(0, data.pageSize);
  }
}

Working_Demo

答案 3 :(得分:0)

您可以将page上的mat-paginator事件发射器用作(page)="onPageChange($event)"

<div *ngFor="let item of currentItemsToShow, let i=index;">Hello {{item.name}}</div>    

onPageChange($event) {
        this.currentItemsToShow =  this.items.slice($event.pageIndex*$event.pageSize,
        $event.pageIndex*$event.pageSize + $event.pageSize);
      }

Stackblitz Demo showing Customized Paginatior, try changing paginator values