Published: October 03 2020

Angular 10 - Simple Pagination Example

Example built with Angular 10.1.4

Other versions available:

This is a simple example of how to implement client-side pagination in Angular 10.

The example contains a hard coded array of 150 objects split into 15 pages to demonstrate how the pagination component works. Styling in the example is done with bootstrap 4.5 css but you can style any way you like using the provided css classes, details are provided later in the tutorial.

Here it is in action: (See on StackBlitz at https://stackblitz.com/edit/angular-10-pagination-example)


Angular 10 Pagination Component

Pagination is implemented with the <jw-pagination> component that comes with the jw-angular-pagination package available on npm.

Installation

Install the angular pagination component with the command npm install jw-angular-pagination.

Integration with your Angular 10 app

Import the JwPaginationModule into your app module (app.module.ts) and add it to the imports array to make the <jw-pagination> component available within your Angular module.

This is the app module (app.module.ts) from the example, the pagination module is imported on line 3 and added to the imports on line 10.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { JwPaginationModule } from 'jw-angular-pagination';

import { AppComponent } from './app.component';

@NgModule({
    imports: [
        BrowserModule,
        JwPaginationModule
    ],
    declarations: [
        AppComponent
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }


Usage

There are 2 required properties for using the Angular 10 pagination component:

  • items - the array of items to be paged
  • changePage - a callback function for handling the changePage event

There are also a few optional properties:

  • pageSize - the number of items displayed on each page (defaults to 10)
  • maxPages - the max number of page links to display in the pagination nav (defaults to 10)
  • initialPage - the initial page to display (defaults to 1)


Example App Component

This is the app component (/src/app/app.component.ts) from the example, it creates a hardcoded array of items to be paged in the ngOnInit() method, and updates the current page of items in the onChangePage() callback method.

import { Component, OnInit } from '@angular/core';

@Component({ selector: 'app', templateUrl: 'app.component.html' })
export class AppComponent implements OnInit {
    items = [];
    pageOfItems: Array<any>;

    constructor() { }

    ngOnInit() {
        // an example array of 150 items to be paged
        this.items = Array(150).fill(0).map((x, i) => ({ id: (i + 1), name: `Item ${i + 1}`}));
    }

    onChangePage(pageOfItems: Array<any>) {
        // update current page of items
        this.pageOfItems = pageOfItems;
    }
}


Example App Component Template

This is the app component template (/src/app/app.component.html) from the example, it renders the current page of items using the *ngFor Angular directive on line 5, and includes the pagination component (<jw-pagination ...>) on line 8.

The pagination component is bound to items property of the app component using the Angular model binding attribute [items]="items", and is bound to the onChangePage() method of the app component using the Angular event binding attribute (changePage)="onChangePage($event)".

<!-- main app container -->
<div class="card text-center m-3">
    <h3 class="card-header">Angular 10 Pagination Example</h3>
    <div class="card-body">
        <div *ngFor="let item of pageOfItems">{{item.name}}</div>
    </div>
    <div class="card-footer pb-0 pt-3">
        <jw-pagination [items]="items" (changePage)="onChangePage($event)"></jw-pagination>
    </div>
</div>


Styling the Pagination Component

The JW Angular pagination component is unstyled by default, you can use the below CSS selectors to add your own custom styles.

You can also plug in Bootstrap CSS (3.x or 4.x) which the component is compatible with.

  • .pagination - Pagination component container (ul element)
  • .pagination .page-item - All list items in the pagination component
  • .pagination .page-item .page-link - All pagination links including first, last, previous and next
  • .pagination .number-item - All page numbers (1, 2, 3 etc) pagination elements
  • .pagination .first-item - The 'First' pagination element
  • .pagination .last-item - The 'Last' pagination element
  • .pagination .previous-item - The 'Previous' pagination element
  • .pagination .next-item - The 'Next' pagination element


Hiding Pagination Buttons

To hide any of the buttons you can simply set them to display: none; using the css selectors described above.


Further Customisation of the Pagination Component

If you want to make further customisations such as changing the HTML template of the component, I'd recommend just copying the pagination component code into your own custom Angular component, it's only about 60 lines of code and will give complete flexibility to make any changes you like.

To use this approach you need to install the jw-paginate package from npm with the command npm install jw-paginate. The jw-paginate package contains the core pagination logic used to paginate any array or list of items in javascript. For more info see JavaScript - Pure Pagination Logic in Vanilla JS / TypeScript.

This is the complete code for the Angular pagination component, it's also available on GitHub at https://github.com/cornflourblue/jw-angular-pagination/blob/master/projects/jw-pagination/src/lib/jw-pagination.component.ts.

import { Component, Input, Output, EventEmitter, OnInit, OnChanges, SimpleChanges } from '@angular/core';

import paginate from 'jw-paginate';

@Component({
    selector: 'jw-pagination',
    template: `<ul *ngIf="pager.pages && pager.pages.length" class="pagination">
    <li [ngClass]="{disabled:pager.currentPage === 1}" class="page-item first-item">
        <a (click)="setPage(1)" class="page-link">First</a>
    </li>
    <li [ngClass]="{disabled:pager.currentPage === 1}" class="page-item previous-item">
        <a (click)="setPage(pager.currentPage - 1)" class="page-link">Previous</a>
    </li>
    <li *ngFor="let page of pager.pages" [ngClass]="{active:pager.currentPage === page}" class="page-item number-item">
        <a (click)="setPage(page)" class="page-link">{{page}}</a>
    </li>
    <li [ngClass]="{disabled:pager.currentPage === pager.totalPages}" class="page-item next-item">
        <a (click)="setPage(pager.currentPage + 1)" class="page-link">Next</a>
    </li>
    <li [ngClass]="{disabled:pager.currentPage === pager.totalPages}" class="page-item last-item">
        <a (click)="setPage(pager.totalPages)" class="page-link">Last</a>
    </li>
</ul>`
})

export class JwPaginationComponent implements OnInit, OnChanges {
    @Input() items: Array<any>;
    @Output() changePage = new EventEmitter<any>(true);
    @Input() initialPage = 1;
    @Input() pageSize = 10;
    @Input() maxPages = 10;

    pager: any = {};

    ngOnInit() {
        // set page if items array isn't empty
        if (this.items && this.items.length) {
            this.setPage(this.initialPage);
        }
    }

    ngOnChanges(changes: SimpleChanges) {
        // reset page if items array has changed
        if (changes.items.currentValue !== changes.items.previousValue) {
            this.setPage(this.initialPage);
        }
    }

    setPage(page: number) {
        // get new pager object for specified page
        this.pager = paginate(this.items.length, page, this.pageSize, this.maxPages);

        // get new page of items from items array
        var pageOfItems = this.items.slice(this.pager.startIndex, this.pager.endIndex + 1);

        // call change page function in parent component
        this.changePage.emit(pageOfItems);
    }
}

 


Need Some Angular 10 Help?

Search fiverr for freelance Angular 10 developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by