• Skip to main content
  • Skip to primary sidebar

Web Development Archive

  • Archive
You are here: Home / Angular / Pagination Service

Pagination Service

Ha a PaginationService providedIn: 'root'-tal singleton, akkor az összes komponens ugyanazt a page signalt fogja használni. Emiatt ha két külön lista is van az oldalon, azok elcsúsznak egymással, mivel közös állapotot használnak.

Megoldás: Komponens szintű provider

pagination-service.ts

import { Injectable, signal, computed, Signal } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class PaginationService {
public page = signal(1);
public perPage = 5;

public setPage(page: number): void {
this.page.set(page);
}

public paginate<T>(data: T[]): Signal<T[]> {
return computed(() => {
const start = (this.page() - 1) * this.perPage;
return data.slice(start, start + this.perPage);
});
}
}

component.ts

export class News {
private readonly paginator = inject(PaginationService);
public readonly paginatedNews = this.paginator.paginate(this.news());

public readonly page = this.paginator.page;
public readonly perPage = this.paginator.perPage;

private scrollToTop(): void {
if (typeof window === 'undefined' || typeof document === 'undefined') {
return;
}

// Kis delay, hogy mobilon is biztosan a végleges layout után fusson
setTimeout(() => {
const anchor = document.getElementById('news-top');
if (anchor) {
anchor.scrollIntoView({
behavior: 'smooth',
block: 'start',
});
} else {
// fallback
window.scrollTo({ top: 0, behavior: 'smooth' });
}
}, 50);
}

public next(): void {
this.paginator.setPage(this.page() + 1);
this.scrollToTop();
}

public prev(): void {
if (this.page() > 1) {
this.paginator.setPage(this.page() - 1);
this.scrollToTop();
}
}
}

template.html

@for (item of paginatedNews(); track item.id) {
<app-card>...</app-card>
}

<div class="flex justify-center items-center gap-4 mt-6 mb-10">
<button
class="dds-button"
[disabled]="page() === 1"
(click)="prev()"
>
Előző
</button>

<span class="dds-text text-lg font-semibold">
{{ page() }}
</span>

<button
class="dds-button"
[disabled]="paginatedNews().length < perPage"
(click)="next()"
>
Következő
</button>
</div>

Filed Under: Angular

About Gabor Flamich

I'm a web developer and designer based in Budapest, Hungary. In recent years, I've documented hundreds of solutions I came across during development. This site is an archive for useful code snippets on WordPress, Genesis Framework and WooCommerce. If You have any questions related to WordPress development, get in touch!

Primary Sidebar

  • angular.io
© 2026 WP Flames - All Right Reserved