Elevating Our Angular Data Table: Adding Pagination

Welcome Back to Our Angular Journey

Pathakrajaryan
2 min readNov 29, 2023

In the previous installment, we laid the groundwork for our dynamic Angular data table. Now, we’re elevating it by integrating one of the essential features: pagination. Let’s explore how this functionality enhances the table’s interactivity and user experience.

1. Setting Up Pagination Inputs

We begin by enhancing our generic-data-table component with crucial @Input() properties:

@Input() totalItems: number = 0;
@Input() isServerSidePagination: boolean = true;

2. Integrating the Paginator in HTML

We incorporate Angular Material’s paginator in our generic-data-table component’s template, offering a user-friendly interface for data navigation:

<mat-paginator [length]="totalItems" [pageSize]="pageSize" 
[pageSizeOptions]="[5, 10, 20, 500, 750, 1000]"
(page)="onPaginateChange($event)" showFirstLastButtons>
</mat-paginator>

3. Handling Page Changes with @Output() pageChanged

The onPaginateChange function is the core of our pagination logic. It’s triggered every time the user interacts with the pagination controls, handling both client-side and server-side pagination scenarios.

onPaginateChange(event: PageEvent) {
if (this.isServerSidePagination) {
// Emitting pageChanged event for the parent component
this.pageChanged.emit({
pageIndex: event.pageIndex,
pageSize: event.pageSize
});
} else {
// Client-side pagination handling
const startIndex = event.pageIndex * event.pageSize;
const endIndex = startIndex + event.pageSize;
this.displayDataSource = this.dataSource.slice(startIndex, endIndex);
}
}

In case server-side pagination is true, We’ve introduced the @Output() pageChanged Event Emitter to handle server-side-pagination.

onPaginateChange leverages Angular’s event emitter to notify the parent component about the page change. It emits page changed with the new page index and page size as its payload.

Bridging Components with @Output() pageChanged

Our @Output() pageChanged event plays a vital role in server-side pagination. It's the bridge between the generic-data-table and its parent component, enabling dynamic data fetching based on user interaction

Integrating Pagination in the Parent Component

 <app-generic-data-table 
[dataSource]="dataSource"
[columns]="columns"
[totalItems]="totalItemCount"
[isServerSidePagination]="true"
(pageChanged)="pageChanged($event.pageIndex, $event.pageSize)" >
</app-generic-data-table>

Wrapping Up Pagination

With mat-paginator and the onPaginateChange method, our data table becomes adept at handling large datasets, offering smooth navigation and accessibility. This setup not only enhances the table's functionality but also ensures a seamless user experience.

In our next segment, we will explore adding sorting capabilities to further refine our data table’s functionality

--

--