Skip to content

Instantly share code, notes, and snippets.

@tinmegali
Last active April 3, 2022 18:35
Show Gist options
  • Save tinmegali/5b23ae3bb5a2a6b5c500fa50fbb3d8b6 to your computer and use it in GitHub Desktop.
Save tinmegali/5b23ae3bb5a2a6b5c500fa50fbb3d8b6 to your computer and use it in GitHub Desktop.
Manually adding pagination to Angular frontend.

route.ts

Add the following class to file

import {ActivatedRouteSnapshot, Resolve, RouterStateSnapshot, Routes} from '@angular/router';
//...
import {JhiPaginationUtil} from 'ng-jhipster';
import {Injectable} from '@angular/core';

@Injectable()
export class EntityPagingParams implements Resolve<any> {
    constructor(private paginationUtil: JhiPaginationUtil) {}

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        const page = route.queryParams['page'] ? route.queryParams['page'] : '1';
        const sort = route.queryParams['sort'] ? route.queryParams['sort'] : 'id,asc';
        return {
            page: this.paginationUtil.parsePage(page),
            predicate: this.paginationUtil.parsePredicate(sort),
            ascending: this.paginationUtil.parseAscending(sort)
        };
    }
}

Edit the Routes const to the following

 export const entityRoute: Routes = [
     {
         path: 'entity',
         component: PesquisaQuestaoDiscRespostaComponent,
\!h        resolve: {
\!h            'pagingParams': EntityPagingParams
\!h        },

Module.ts

Import and add PagingParams to Providers

    providers: [
        PesquisaQuestaoDiscRespostaService,
        PesquisaQuestaoDiscRespostaPopupService,
\!h        EntityPagingParams
    ],

Component.ts

\\ Import `ActivatedRoute` and `Router`
import {ActivatedRoute, Router} from '@angular/router';
\\ Add variable 'routeData' and 'previous page'
export class PesquisaQuestaoDiscRespostaComponent implements OnInit, OnDestroy {

    entities: Entity[];
    //...
    totalItems: number;
\!h    routeData: any;
\!h    previousPage: any;

  constructor(
        private pesquisaQuestaoDiscRespostaService: PesquisaQuestaoDiscRespostaService,
        private jhiAlertService: JhiAlertService,
        private eventManager: JhiEventManager,
        private parseLinks: JhiParseLinks,
        private principal: Principal,
\!h        private activatedRoute: ActivatedRoute,
\!h        private router: Router,
    )

In constructor body, replace the following code:

      constructor(
        //...) 
      {
        this.pesquisaQuestaoDiscRespostas = [];
        this.itemsPerPage = ITEMS_PER_PAGE;

\!h        this.page = 0;
\!h        this.links = {
\!h            last: 0
\!h        };
\!h        this.predicate = 'id';
\!h        this.reverse = true;
      }

by

        this.routeData = this.activatedRoute.data.subscribe((data) => {
            this.page = data['pagingParams'].page;
            this.previousPage = data['pagingParams'].page;
            this.reverse = data['pagingParams'].ascending;
            this.predicate = data['pagingParams'].predicate;
        });

Edit ngOnInit

    ngOnInit() {
        this.principal.identity().then((account) => {
            this.currentAccount = account;
            this.transition();
            this.registerChangeInEntities();
        });
    }

Edit ngOnDestroy

    ngOnDestroy() {
\!h        this.routeData.unsubscribe();
        this.eventManager.destroy(this.eventSubscriber);
    }

Edit loadAll

     loadAll() {
         this.pesquisaQuestaoDiscRespostaService.query({
\!h           page: this.page - 1,
             size: this.itemsPerPage,
             sort: this.sort()
         }).subscribe(

Edit loadPage

    loadPage(page: number) {
        if (page !== this.previousPage) {
            this.previousPage = page;
            this.transition();
        }
    }

Edit transition

    transition() {
        this.router.navigate(['/entity'], {
            queryParams: {
                page: this.page,
                sort: this.predicate + ',' + (this.reverse ? 'asc' : 'desc')
            }
         });
        this.loadAll();
     }

Edit registerChangeInEntities

     registerChangeInEntities() {
// remove        this.eventSubscriber = this.eventManager.subscribe('entityModification', (response) => this.reset());
\!h        this.eventSubscriber =
\!h            this.eventManager.subscribe(
\!h                'entityModification', (response) => this.loadAll());
     }

Edit onSuccess

     private onSuccess(data, headers) {
         this.links = this.parseLinks.parse(headers.get('link'));
         this.totalItems = headers.get('X-Total-Count');
\!h        this.queryCount = this.totalItems;
\!h        this.entities = data;
        // for (let i = 0; i < data.length; i++) {
        //     this.pesquisaQuestaoDiscRespostas.push(data[i]);
        // }
     }

Component.hml

Add after </table></div>

    <!-- Pagination -->
    <div *ngIf="totalItems">
        <div class="row justify-content-center">
            <jhi-item-count [page]="page" [total]="queryCount"
                            [itemsPerPage]="itemsPerPage"></jhi-item-count>
        </div>
        <div class="row justify-content-center">
            <ngb-pagination [collectionSize]="totalItems"
                            [(page)]="page" [pageSize]="itemsPerPage"
                            [maxSize]="5" [rotate]="true"
                            [boundaryLinks]="true"
                            (pageChange)="loadPage(page)"></ngb-pagination>
        </div>
    </div>

If comming from Infinity Scroll, switch the line

<tbody infinite-scroll (scrolled)="loadPage(page + 1)" [infiniteScrollDisabled]="page >= links['last']" [infiniteScrollDistance]="0">

by <tbody>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment