Skip to content

Instantly share code, notes, and snippets.

@max-lt
Created December 1, 2023 10:32
Show Gist options
  • Save max-lt/2bd23071308ca81e1d879200f7c34de6 to your computer and use it in GitHub Desktop.
Save max-lt/2bd23071308ca81e1d879200f7c34de6 to your computer and use it in GitHub Desktop.
Angular pagination
<!-- Pagination -->
<ul class="pagination">
<li class="page-item">
<button class="page-link" (click)="goPrevious()" [disabled]="0 === current">Previous</button>
</li>
<li class="page-item" *ngFor="let n of nums;">
<button class="page-link" (click)="goPage(n)" [disabled]="n - 1 === current || n === '...'">{{ n }}</button>
</li>
<li class="page-item">
<button class="page-link" (click)="goNext()" [disabled]="cnt - 1 === current">Next</button>
</li>
</ul>
@import 'custom-bootstrap';
.pagination {
margin-bottom: 0;
}
.page-link:disabled {
opacity: 0.65;
}
.page-link:focus {
box-shadow: none;
}
.page-link:disabled:hover {
color: $pagination-color;
background-color: $pagination-bg;
border: $pagination-border-width solid $pagination-border-color;
}
import { Component, Input, EventEmitter, OnInit, Output } from '@angular/core';
import log from '~/log';
@Component({
selector: 'app-pagination',
templateUrl: './index.html',
styleUrls: ['./style.scss']
})
export class PaginationComponent implements OnInit {
@Input()
max = 10;
cnt;
@Input()
set count(val) {
this.cnt = val;
this.render();
}
@Input()
current;
@Output()
change: EventEmitter<number>;
nums: any[];
constructor() {
this.change = new EventEmitter();
}
ngOnInit() {
this.render();
}
render() {
if (!this.cnt) {
return;
}
const nums: any[] = (new Array(parseInt(this.cnt) || 0))
.fill(0)
.map((v, i) => i + 1);
const max = this.max;
const len = nums.length;
if (len > max) {
const mid = Math.floor(max / 2);
nums.splice(mid, (len - (mid * 2)) - 1);
nums[mid] = '...';
}
this.nums = nums;
}
goPrevious() {
log.trace('go prev page', this.current - 1);
this.change.emit(this.current - 1);
}
goNext() {
log.trace('go next page', this.current + 1);
this.change.emit(this.current + 1);
}
goPage(n) {
log.trace('go to page', n - 1);
this.change.emit(n - 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment