All files / src/app/shared/components/common/paging paging.component.ts

88.88% Statements 16/18
81.81% Branches 9/11
80% Functions 4/5
94.11% Lines 16/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 582x 2x               2x       6x   6x   6x     5x 5x                 2x 2x                     5x       5x 3x 1x   2x       2x      
import { ViewportScroller } from '@angular/common';
import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnChanges, Output } from '@angular/core';
 
@Component({
  selector: 'ish-paging',
  templateUrl: './paging.component.html',
  styleUrls: ['./paging.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PagingComponent implements OnChanges {
  @Input({ required: true }) currentPage: number;
  @Input({ required: true }) lastPage: number;
 
  @Output() goToPage: EventEmitter<number> = new EventEmitter<number>();
 
  pageIndices: number[] = [];
 
  constructor(private scroller: ViewportScroller) {}
 
  ngOnChanges(): void {
    if (this.currentPage && this.lastPage) {
      this.pageIndices = this.getPages(this.currentPage, this.lastPage);
    }
  }
  /**
   * If the user changes the page the goToPage event is emitted
   *
   * @param page : changed page number
   */
  setPage(page: number) {
    this.goToPage.emit(page);
    this.scroller.scrollToPosition([0, 0]);
  }
 
  /**
   * Determines the page array - elements with the value of -1 will be shown as ...
   *
   * @param current current page
   * @param total   number of pages
   * @returns       pages array
   */
  private getPages(current: number, total: number): number[] {
    Iif (total <= 8) {
      return [...Array(total).keys()].map(x => x + 1);
    }
 
    if (current > 4) {
      if (current >= total - 3) {
        return [1, -1, total - 5, total - 4, total - 3, total - 2, total - 1, total];
      } else {
        return [1, -1, current - 2, current - 1, current, current + 1, current + 2, -1, total];
      }
    }
 
    return [1, 2, 3, 4, 5, 6, -1, total];
  }
}