Example
Here’s a basic example of Angular Material Table with pagination:
import { Component } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
@Component({
selector: 'app-pagination-demo',
template: `
<div>
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef> ID </th>
<td mat-cell *matCellDef="let element"> {{element.id}} </td>
</ng-container>
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> Name </th>
<td mat-cell *matCellDef="let element"> {{element.name}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator [length]="100" [pageSize]="10" showFirstLastButtons></mat-paginator>
</div>
`,
styleUrls: ['./pagination-demo.component.css']
})
export class PaginationDemoComponent {
displayedColumns: string[] = ['id', 'name'];
dataSource = new MatTableDataSource(ELEMENT_DATA);
}
const ELEMENT_DATA = Array.from({ length: 100 }, (_, k) => ({ id: k + 1, name: `Name ${k + 1}` }));
Output
The above code creates a table with pagination, allowing users to navigate through pages of data. The paginator at the bottom helps in navigating the table efficiently.
Displaying Paginated Data
Displaying paginated data is the first step in implementing pagination. It involves fetching a subset of data from a larger dataset & showing it to the user. In Angular, this is typically done by splitting the data into smaller chunks & rendering only the required portion.
Let’s understand this in step by step manner:
1. Setting Up the Angular Project
First, ensure you have Angular installed. If not, you can install it using the following command:
npm install -g @angular/cli
Create a new Angular project:
ng new pagination-example
cd pagination-example
2. Creating a Data Service
To simulate pagination, we’ll create a service that provides a large dataset. Run the following command to generate a service:
ng generate service data
In the `data.service.ts` file, add a method to return a large dataset:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
private data = Array.from({ length: 100 }, (_, i) => `Item ${i + 1}`);
getData(page: number, pageSize: number): string[] {
const startIndex = (page - 1) pageSize;
const endIndex = startIndex + pageSize;
return this.data.slice(startIndex, endIndex);
}
}
Here, we’ve created a dataset with 100 items. The `getData` method takes `page` & `pageSize` as inputs & returns a subset of the data.
3. Displaying Data in a Component
Next, let’s create a component to display the paginated data. Run the following command:
ng generate component paginated-list
In the `paginated-list.component.ts` file, inject the `DataService` & fetch the data:
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
@Component({
selector: 'app-paginated-list',
templateUrl: './paginated-list.component.html',
styleUrls: ['./paginated-list.component.css']
})
export class PaginatedListComponent implements OnInit {
items: string[] = [];
currentPage = 1;
pageSize = 10;
constructor(private dataService: DataService) {}
ngOnInit(): void {
this.loadData();
}
loadData(): void {
this.items = this.dataService.getData(this.currentPage, this.pageSize);
}
}
In the `paginated-list.component.html` file, display the data:
<div>
<ul>
<li ngFor="let item of items">{{ item }}</li>
</ul>
</div>
4. Testing the Pagination
Run the Angular application using:
ng serve
Open your browser & navigate to `http://localhost:4200`. You should see the first 10 items displayed.
Angular Pagination Example
Another approach is to implement custom pagination in Angular without relying on external libraries. This gives full control over functionality and styling.
Example
import { Component } from '@angular/core';
@Component({
selector: 'app-custom-pagination',
template: `
<div *ngFor="let item of paginatedItems">{{ item }}</div>
<button (click)="prevPage()" [disabled]="currentPage === 1">Previous</button>
<button (click)="nextPage()" [disabled]="currentPage === totalPages">Next</button>
`,
})
export class CustomPaginationComponent {
items = Array.from({ length: 50 }, (_, i) => `Item ${i + 1}`);
currentPage = 1;
itemsPerPage = 10;
get paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage;
return this.items.slice(start, start + this.itemsPerPage);
}
get totalPages() {
return Math.ceil(this.items.length / this.itemsPerPage);
}
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++;
}
}
prevPage() {
if (this.currentPage > 1) {
this.currentPage--;
}
}
}
Explanation
This code demonstrates a manual approach to paginate an array of items. The navigation buttons dynamically update the displayed items.
Paging with Group By
Sometimes, data needs to be grouped by a specific attribute before applying pagination. Angular allows developers to achieve this efficiently.
Example
const groupedData = data.reduce((acc, item) => {
const group = item.category;
acc[group] = acc[group] || [];
acc[group].push(item);
return acc;
}, {});
Usage
Pagination in Angular is widely used in web applications for efficient data rendering. It is common in:
- E-commerce websites
- Admin dashboards
- Data reporting tools
Paginator Component Demo
The Angular Material paginator provides an excellent demo of pagination capabilities. You can configure it to set:
- Page size
- Page ranges
- Navigation options
Remote Paging
Remote paging is used when data is fetched from a server. This approach is efficient as it retrieves only the data required for the current page.
Example
fetchData(page: number, pageSize: number) {
this.httpClient.get(`/api/data?page=${page}&pageSize=${pageSize}`)
.subscribe(response => this.data = response);
}
Remote Paging with Custom Template
You can create a custom template for remote paging using Angular Material or Bootstrap.
Pagination Styling in Angular
Styling can enhance the look and feel of your pagination component.
Defining a Color Palette
.paginator {
background-color: #f5f5f5;
padding: 10px;
border-radius: 5px;
}
.paginator button {
margin: 0 5px;
}
Using Schemas
In Angular, schemas can be used to define the structure of components, improving validation and customization.
Pagination Style Example
Here is a styled pagination component:
<div class="pagination">
<button (click)="prevPage()" [disabled]="currentPage === 1">Previous</button>
<span>Page {{currentPage}} of {{totalPages}}</span>
<button (click)="nextPage()" [disabled]="currentPage === totalPages">Next</button>
</div>
Frequently Asked Questions
What is the purpose of pagination in Angular?
Pagination splits large datasets into smaller chunks for better performance and usability.
How do you implement custom pagination in Angular?
By slicing data arrays based on the current page and items per page, as shown in the examples above.
What is the difference between local and remote pagination?
Local pagination uses data already loaded into the browser, while remote pagination fetches data from the server for each page.
Conclusion
Pagination in Angular is a powerful feature that improves performance and user experience. In this article, we discussed various methods and examples of implementing pagination, from basic Angular Material paginator to custom implementations.