Simple Pagination in Angular
Pagination logic and its implementation in angular
Content Covered
Pagination logic
Live Demo of stackBlitz with code
Here we are going to cover custom basic pagination without any external package, we are going to keep it short and crisp
Logic for pagination:
startIndex=(current page no-1) X rows per page
endIndex=current page no X rows per page
Below is the equivalent code snippet for the same in the code
startIndex = (
this.page
- 1) * this.limit;
endIndex =
this.page
* this.limit;
On change of rows per page, we are getting the rows limit from the dropdown menu on the basis of which we are calculating total pages and calling the display function to render the data
pageLengthChange(value) {
this.limit = value;
this.totalPages = Math.ceil(
this.data
.length / value);
this.display();
}
Rendering the pagination and dataset:
Here we are calculating the start and end point of the page in order to display data rows based on the selected rows limit by the user
this.pageArray is used to display page numbers dynamically
this.displayData is used to slice the actual data and display the selected rows
display() {
let pages = [];
this.startIndex = (
this.page
- 1) * this.limit;
this.endIndex =
this.page
* this.limit;
for (let i = 1; i <= this.totalPages; i++) {
pages.push(i);
}
this.pageArray = pages.slice(
this.page
- 1,
this.page
+ 2);
this.displayData =
this.data
.slice(this.startIndex, this.endIndex);
}
Now we have the functions which are called on page change:
nextPage() {
if (this.endIndex <
this.data
.length) {
this.page
+= 1;
this.display();
}
}
goToPage(page: string) {
console.log(page);
this.page
= parseInt(page);
this.display();
}
PrevPage() {
if (this.startIndex > 0) {
this.page
-= 1;
this.display();
}
}
goToPage function is called when clicking on a specific page number where we are taking the page number and calling the display function to change the dataset according to that page
Similarly, on click of the next and previous page buttons, we are incrementing and decrementing page number (i.e. this.page ) and calling the display function
For more details, you can check the live demo on the below link
https://stackblitz.com/edit/angular-ivy-srbjsr?file=src%2Fapp%2Fapp.component.ts