ranyeli
9/20/2017 - 1:11 AM

pagination component

basic pagination

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

import 'rxjs/add/operator/toPromise';

@Component({
  selector: 'app-pagination',
  templateUrl: './pagination.component.html',
  styleUrls: ['./pagination.component.css']
})
export class PaginationComponent implements OnInit, OnChanges {

  pages: number[] = [];

  @Input() page: number; // the current page
  @Input() count: number; // how many total items there are in all pages
  @Input() perPage: number; // how many items we want to show per page
  @Input() pagesToShow: number; // how many pages between next/prev
  @Input() pagesToShowDefault: number; // default number of pages between next/prev
  @Input() loading: boolean; // check if content is being loaded
  @Input() initial: boolean; // to test if the properties changes are because of the page load/reload

  @Output() goPrev = new EventEmitter<boolean>();
  @Output() goNext = new EventEmitter<boolean>();
  @Output() goPage = new EventEmitter<number>();

  constructor() { }

  ngOnInit() {
    if (this.pages.length < 1) {
      this.populatePagesToShow();
    }
  }

  ngOnChanges(changes: SimpleChanges): void {

    if (changes.count && !changes.initial) {
      this.pagesToShow = Math.ceil(this.count / this.perPage) >= this.pagesToShowDefault ? this.pagesToShowDefault : Math.ceil(this.count / this.perPage);
      console.log("show pages = ", this.pagesToShow);
      this.populatePagesToShow();
      if (Math.max(...this.pages) < this.page) {
        this.onPage(Math.max(...this.pages));
      }
    }
    if ((changes.page || changes.count) && !(changes.page && changes.count)) {
      this.getPages();
    }
  }

  populatePagesToShow() {
    this.pages = Array.from({ length: this.pagesToShow }, (v, k) => k + 1);
    console.log("pages = ", this.pages);
  }

  getMax(): number {
    let max = this.perPage * this.page;
    if (max > this.count) {
      max = this.count;
    }
    return max;
  }

  onPage(n: number): void {
    this.goPage.emit(n);

  }

  onPrev(): void {
    this.goPrev.emit(true);
  }

  onNext(next: boolean): void {
    this.goNext.emit(next);
  }

  totalPages(): number {
    return Math.ceil(this.count / this.perPage) || 0;
  }

  lastPage(): boolean {
    return this.perPage * this.page >= this.count;
  }

  getPages(): void {
    if (this.page >= Math.max(...this.pages) && this.page < this.totalPages()) {
      this.pages.push(Math.max(...this.pages) + 1);
      this.pages.shift();
    }
    else if (this.page <= Math.min(...this.pages) && Math.min(...this.pages) > 1) {
      this.pages.unshift(Math.min(...this.pages) - 1);
      this.pages.pop();
    }
  }
}