让我们从服务中读取数据开始(在服务中,我们从 json 文件中读取数据)
export class AppComponent implements OnInit {
public products: any[] = [];
curPage: number;
pageSize: number;
constructor(private _Products: ProductService) { }
ngOnInit(): void {
this._Products.getJSON().subscribe(response => {
this.products = response.items;
});
this.curPage = 1;
this.pageSize = 10; // any page size you want
}
numberOfPages() {
return Math.ceil(this.products.length / this.pageSize);
};
}
这里我们添加了两个变量,curPage 和pageSize,可以根据需要进行更新。 (单击)会将用户导航到所需的页面。您可以根据需要更新分页控件的外观。
最后在你的 html 中:
<table class="table table-sm table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of products | slice: (curPage * pageSize) - pageSize :curPage * pageSize">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
</tr>
</tbody>
</table>
<p class="pagination">
<button [disabled]="curPage == 1" (click)="curPage = curPage - 1">PREV</button>
<span>Page {{curPage}} of {{ numberOfPages() }}</span>
<button [disabled]="curPage >= list.length/pageSize" (click)="curPage = curPage + 1">NEXT</button>
</p>
Stackblitz Here
另一种方法是使用 NPM 包:ngx-pagination
第 1 步:在终端上运行以下命令
npm install ngx-pagination --save
第 2 步:从 Service 读取数据
export class AppComponent implements OnInit {
public products: any[] = [];
constructor(private _Products: ProductService) { }
ngOnInit(): void {
this._Products.getJSON().subscribe(response => {
this.products = response.items;
});
}
}
第三步:在 app.module.ts 中导入依赖
import { NgxPaginationModule } from 'ngx-pagination';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
NgxPaginationModule --> this line
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
现在让我们看一下 app.module.ts 中的代码,其中导入了 ngx-pagination 模块
第 4 步:从 app.component.html 更新视图
<table class="table table-sm table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of products | paginate:{itemsPerPage: 5, currentPage:p}">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
</tr>
</tbody>
</table>
<pagination-controls (pageChange)="p=$event"></pagination-controls>
第 5 步:运行应用
使用 npm start 在终端上运行应用程序
Stackblitz Here