Getting Started
UI
Components
- Accordion
- Alert
- Alert Dialog
- Aspect Ratio
- Autocomplete
- Avatar
- Badge
- Breadcrumb
- Button
- Button Group
- Calendar
- Card
- Carousel
- Checkbox
- Collapsible
- Combobox
- Command
- Context Menu
- Data Table
- Date Picker
- Dialog
- Dropdown Menu
- Empty
- Field
- Hover Card
- Icon
- Input Group
- Input OTP
- Input
- Item
- Kbd
- Label
- Menubar
- Native Select
- Navigation Menu
- Pagination
- Popover
- Progress
- Radio Group
- Resizable
- Scroll Area
- Select
- Separator
- Sheet
- Sidebar
- Skeleton
- Slider
- Sonner (Toast)
- Spinner
- Switch
- Table
- Tabs
- Textarea
- Toggle
- Toggle Group
- Tooltip
Forms
Stack
Pagination
Pagination with page navigation, next and previous links.
import { Component } from '@angular/core';
import { HlmPaginationImports } from '@spartan-ng/helm/pagination';
@Component({
selector: 'spartan-pagination-preview',
imports: [HlmPaginationImports],
template: `
<nav hlmPagination>
<ul hlmPaginationContent>
<li hlmPaginationItem>
<hlm-pagination-previous link="/components/menubar" />
</li>
<li hlmPaginationItem>
<a hlmPaginationLink link="#">1</a>
</li>
<li hlmPaginationItem>
<a hlmPaginationLink link="#" isActive>2</a>
</li>
<li hlmPaginationItem>
<a hlmPaginationLink link="#">3</a>
</li>
<li hlmPaginationItem>
<hlm-pagination-ellipsis />
</li>
<li hlmPaginationItem>
<hlm-pagination-next link="/components/popover" />
</li>
</ul>
</nav>
`,
})
export class PaginationPreview {}Installation
ng g @spartan-ng/cli:ui paginationnx g @spartan-ng/cli:ui paginationimport { DestroyRef, ElementRef, HostAttributeToken, Injector, PLATFORM_ID, effect, inject, runInInjectionContext } from '@angular/core';
import { clsx, type ClassValue } from 'clsx';
import { isPlatformBrowser } from '@angular/common';
import { twMerge } from 'tailwind-merge';
export function hlm(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
// Global map to track class managers per element
const elementClassManagers = new WeakMap<HTMLElement, ElementClassManager>();
// Global mutation observer for all elements
let globalObserver: MutationObserver | null = null;
const observedElements = new Set<HTMLElement>();
interface ElementClassManager {
element: HTMLElement;
sources: Map<number, { classes: Set<string>; order: number }>;
baseClasses: Set<string>;
isUpdating: boolean;
nextOrder: number;
hasInitialized: boolean;
restoreRafId: number | null;
/** Transitions are suppressed until the first effect writes correct classes */
transitionsSuppressed: boolean;
/** Original inline transition value to restore after suppression (empty string = none was set) */
previousTransition: string;
/** Original inline transition priority to preserve !important when restoring */
previousTransitionPriority: string;
}
let sourceCounter = 0;
/**
* This function dynamically adds and removes classes for a given element without requiring
* the a class binding (e.g. `[class]="..."`) which may interfere with other class bindings.
*
* 1. This will merge the existing classes on the element with the new classes.
* 2. It will also remove any classes that were previously added by this function but are no longer present in the new classes.
* 3. Multiple calls to this function on the same element will be merged efficiently.
*/
export function classes(computed: () => ClassValue[] | string, options: ClassesOptions = {}) {
runInInjectionContext(options.injector ?? inject(Injector), () => {
const elementRef = options.elementRef ?? inject(ElementRef);
const platformId = inject(PLATFORM_ID);
const destroyRef = inject(DestroyRef);
const baseClasses = inject(new HostAttributeToken('class'), { optional: true });
const element = elementRef.nativeElement;
// Create unique identifier for this source
const sourceId = sourceCounter++;
// Get or create the class manager for this element
let manager = elementClassManagers.get(element);
if (!manager) {
// Initialize base classes from variation (host attribute 'class')
const initialBaseClasses = new Set<string>();
if (baseClasses) {
toClassList(baseClasses).forEach((cls) => initialBaseClasses.add(cls));
}
manager = {
element,
sources: new Map(),
baseClasses: initialBaseClasses,
isUpdating: false,
nextOrder: 0,
hasInitialized: false,
restoreRafId: null,
transitionsSuppressed: false,
previousTransition: '',
previousTransitionPriority: '',
};
elementClassManagers.set(element, manager);
// Setup global observer if needed and register this element
setupGlobalObserver(platformId);
observedElements.add(element);
// Suppress transitions until the first effect writes correct classes and
// the browser has painted them. This prevents CSS transition animations
// during hydration when classes change from SSR state to client state.
if (isPlatformBrowser(platformId)) {
manager.previousTransition = element.style.getPropertyValue('transition');
manager.previousTransitionPriority = element.style.getPropertyPriority('transition');
element.style.setProperty('transition', 'none', 'important');
manager.transitionsSuppressed = true;
}
}
// Assign order once at registration time
const sourceOrder = manager.nextOrder++;
function updateClasses(): void {
// Get the new classes from the computed function
const newClasses = toClassList(computed());
// Update this source's classes, keeping the original order
manager!.sources.set(sourceId, {
classes: new Set(newClasses),
order: sourceOrder,
});
// Update the element
updateElement(manager!);
// Re-enable transitions after the first effect writes correct classes.
// Deferred to next animation frame so the browser paints the class change
// with transitions disabled first, then re-enables them.
if (manager!.transitionsSuppressed) {
manager!.transitionsSuppressed = false;
manager!.restoreRafId = requestAnimationFrame(() => {
manager!.restoreRafId = null;
restoreTransitionSuppression(manager!);
});
}
}
// Register cleanup with DestroyRef
destroyRef.onDestroy(() => {
if (manager!.restoreRafId !== null) {
cancelAnimationFrame(manager!.restoreRafId);
manager!.restoreRafId = null;
}
if (manager!.transitionsSuppressed) {
manager!.transitionsSuppressed = false;
restoreTransitionSuppression(manager!);
}
// Remove this source from the manager
manager!.sources.delete(sourceId);
// If no more sources, clean up the manager
if (manager!.sources.size === 0) {
cleanupManager(element);
} else {
// Update element without this source's classes
updateElement(manager!);
}
});
/**
* We need this effect to track changes to the computed classes. Ideally, we would use
* afterRenderEffect here, but that doesn't run in SSR contexts, so we use a standard
* effect which works in both browser and SSR.
*/
effect(updateClasses);
});
}
function restoreTransitionSuppression(manager: ElementClassManager): void {
const prev = manager.previousTransition;
if (prev) {
manager.element.style.setProperty('transition', prev, manager.previousTransitionPriority || undefined);
} else {
manager.element.style.removeProperty('transition');
}
}
// eslint-disable-next-line @typescript-eslint/no-wrapper-object-types
function setupGlobalObserver(platformId: Object): void {
if (isPlatformBrowser(platformId) && !globalObserver) {
// Create single global observer that watches the entire document
globalObserver = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
const element = mutation.target as HTMLElement;
const manager = elementClassManagers.get(element);
// Only process elements we're managing
if (manager && observedElements.has(element)) {
if (manager.isUpdating) continue; // Ignore changes we're making
// Update base classes to include any externally added classes
const currentClasses = toClassList(element.className);
const allSourceClasses = new Set<string>();
// Collect all classes from all sources
for (const source of manager.sources.values()) {
for (const className of source.classes) {
allSourceClasses.add(className);
}
}
// Any classes not from sources become new base classes
manager.baseClasses.clear();
for (const className of currentClasses) {
if (!allSourceClasses.has(className)) {
manager.baseClasses.add(className);
}
}
updateElement(manager);
}
}
}
});
// Start observing the entire document for class attribute changes
globalObserver.observe(document, {
attributes: true,
attributeFilter: ['class'],
subtree: true, // Watch all descendants
});
}
}
function updateElement(manager: ElementClassManager): void {
if (manager.isUpdating) return; // Prevent recursive updates
manager.isUpdating = true;
// Handle initialization: capture base classes after first source registration
if (!manager.hasInitialized && manager.sources.size > 0) {
// Get current classes on element (may include SSR classes)
const currentClasses = toClassList(manager.element.className);
// Get all classes that will be applied by sources
const allSourceClasses = new Set<string>();
for (const source of manager.sources.values()) {
source.classes.forEach((className) => allSourceClasses.add(className));
}
// Only consider classes as "base" if they're not produced by any source
// This prevents SSR-rendered classes from being preserved as base classes
currentClasses.forEach((className) => {
if (!allSourceClasses.has(className)) {
manager.baseClasses.add(className);
}
});
manager.hasInitialized = true;
}
// Get classes from all sources, sorted by registration order (later takes precedence)
const sortedSources = Array.from(manager.sources.entries()).sort(([, a], [, b]) => a.order - b.order);
const allSourceClasses: string[] = [];
for (const [, source] of sortedSources) {
allSourceClasses.push(...source.classes);
}
// Combine base classes with all source classes, ensuring base classes take precedence
const classesToApply =
allSourceClasses.length > 0 || manager.baseClasses.size > 0
? hlm([...allSourceClasses, ...manager.baseClasses])
: '';
// Apply the classes to the element
if (manager.element.className !== classesToApply) {
manager.element.className = classesToApply;
}
manager.isUpdating = false;
}
function cleanupManager(element: HTMLElement): void {
// Remove from global tracking
observedElements.delete(element);
elementClassManagers.delete(element);
// If no more elements being tracked, cleanup global observer
if (observedElements.size === 0 && globalObserver) {
globalObserver.disconnect();
globalObserver = null;
}
}
interface ClassesOptions {
elementRef?: ElementRef<HTMLElement>;
injector?: Injector;
}
// Cache for parsed class lists to avoid repeated string operations
const classListCache = new Map<string, string[]>();
function toClassList(className: string | ClassValue[]): string[] {
// For simple string inputs, use cache to avoid repeated parsing
if (typeof className === 'string' && classListCache.has(className)) {
return classListCache.get(className)!;
}
const result = clsx(className)
.split(' ')
.filter((c) => c.length > 0);
// Cache string results, but limit cache size to prevent memory growth
if (typeof className === 'string' && classListCache.size < 1000) {
classListCache.set(className, result);
}
return result;
}import type, { BooleanInput, NumberInput } from '@angular/cdk/coercion';
import type, { ButtonVariants, buttonVariants, type ButtonVariants } from '@spartan-ng/helm/button';
import type, { RouterLink } from '@angular/router';
import { ChangeDetectionStrategy, Component, Directive, booleanAttribute, computed, input, model, numberAttribute, untracked } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HlmIcon, HlmIconImports } from '@spartan-ng/helm/icon';
import { HlmSelectImports } from '@spartan-ng/helm/select';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { classes } from '@spartan-ng/helm/utils';
import { lucideChevronLeft, lucideChevronRight, lucideEllipsis } from '@ng-icons/lucide';
@Component({
selector: 'hlm-numbered-pagination-query-params',
imports: [
FormsModule,
HlmPagination,
HlmPaginationContent,
HlmPaginationItem,
HlmPaginationPrevious,
HlmPaginationNext,
HlmPaginationLink,
HlmPaginationEllipsis,
HlmSelectImports,
],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="flex items-center justify-between gap-2 px-4 py-2">
<div class="flex items-center gap-1 text-sm text-nowrap text-gray-600">
<b>{{ totalItems() }}</b>
total items |
<b>{{ _lastPageNumber() }}</b>
pages
</div>
<nav hlmPagination>
<ul hlmPaginationContent>
@if (showEdges() && !_isFirstPageActive()) {
<li hlmPaginationItem>
<hlm-pagination-previous
[link]="link()"
[queryParams]="{ page: currentPage() - 1 }"
queryParamsHandling="merge"
/>
</li>
}
@for (page of _pages(); track page) {
<li hlmPaginationItem>
@if (page === '...') {
<hlm-pagination-ellipsis />
} @else {
<a
hlmPaginationLink
[link]="currentPage() !== page ? link() : undefined"
[queryParams]="{ page }"
queryParamsHandling="merge"
[isActive]="currentPage() === page"
>
{{ page }}
</a>
}
</li>
}
@if (showEdges() && !_isLastPageActive()) {
<li hlmPaginationItem>
<hlm-pagination-next
[link]="link()"
[queryParams]="{ page: currentPage() + 1 }"
queryParamsHandling="merge"
/>
</li>
}
</ul>
</nav>
<!-- Show Page Size selector -->
<hlm-select [(ngModel)]="itemsPerPage" class="ml-auto">
<hlm-select-trigger class="w-fit">
<hlm-select-value />
</hlm-select-trigger>
<hlm-select-content *hlmSelectPortal>
<hlm-select-group>
@for (pageSize of _pageSizesWithCurrent(); track pageSize) {
<hlm-select-item [value]="pageSize">{{ pageSize }}</hlm-select-item>
}
</hlm-select-group>
</hlm-select-content>
</hlm-select>
</div>
`,
})
export class HlmNumberedPaginationQueryParams {
/**
* The current (active) page.
*/
public readonly currentPage = model.required<number>();
/**
* The number of items per paginated page.
*/
public readonly itemsPerPage = model.required<number>();
/**
* The total number of items in the collection. Only useful when
* doing server-side paging, where the collection size is limited
* to a single page returned by the server API.
*/
public readonly totalItems = input.required<number, NumberInput>({
transform: numberAttribute,
});
/**
* The URL path to use for the pagination links.
* Defaults to '.' (current path).
*/
public readonly link = input<string>('.');
/**
* The number of page links to show.
*/
public readonly maxSize = input<number, NumberInput>(7, {
transform: numberAttribute,
});
/**
* Show the first and last page buttons.
*/
public readonly showEdges = input<boolean, BooleanInput>(true, {
transform: booleanAttribute,
});
/**
* The page sizes to show.
* Defaults to [10, 20, 50, 100]
*/
public readonly pageSizes = input<number[]>([10, 20, 50, 100]);
protected readonly _pageSizesWithCurrent = computed(() => {
const pageSizes = this.pageSizes();
return pageSizes.includes(this.itemsPerPage())
? pageSizes // if current page size is included, return the same array
: [...pageSizes, this.itemsPerPage()].sort((a, b) => a - b); // otherwise, add current page size and sort the array
});
protected readonly _isFirstPageActive = computed(() => this.currentPage() === 1);
protected readonly _isLastPageActive = computed(() => this.currentPage() === this._lastPageNumber());
protected readonly _lastPageNumber = computed(() => {
if (this.totalItems() < 1) {
// when there are 0 or fewer (an error case) items, there are no "pages" as such,
// but it makes sense to consider a single, empty page as the last page.
return 1;
}
return Math.ceil(this.totalItems() / this.itemsPerPage());
});
protected readonly _pages = computed(() => {
const correctedCurrentPage = outOfBoundCorrection(this.totalItems(), this.itemsPerPage(), this.currentPage());
if (correctedCurrentPage !== this.currentPage()) {
// update the current page
untracked(() => this.currentPage.set(correctedCurrentPage));
}
return createPageArray(correctedCurrentPage, this.itemsPerPage(), this.totalItems(), this.maxSize());
});
}
@Component({
selector: 'hlm-numbered-pagination',
package
*/
export function outOfBoundCorrection(totalItems: number, itemsPerPage: number, currentPage: number): number {
const totalPages = Math.ceil(totalItems / itemsPerPage);
if (totalPages < currentPage && 0 < totalPages) {
return totalPages;
}
if (currentPage < 1) {
return 1;
}
return currentPage;
}
/**
* Returns an array of Page objects to use in the pagination controls.
*
* Copied from 'ngx-pagination' package
*/
export function createPageArray(
currentPage: number,
itemsPerPage: number,
totalItems: number,
paginationRange: number,
): Page[] {
// paginationRange could be a string if passed from attribute, so cast to number.
paginationRange = +paginationRange;
const pages: Page[] = [];
// Return 1 as default page number
// Make sense to show 1 instead of empty when there are no items
const totalPages = Math.max(Math.ceil(totalItems / itemsPerPage), 1);
const halfWay = Math.ceil(paginationRange / 2);
const isStart = currentPage <= halfWay;
const isEnd = totalPages - halfWay < currentPage;
const isMiddle = !isStart && !isEnd;
const ellipsesNeeded = paginationRange < totalPages;
let i = 1;
while (i <= totalPages && i <= paginationRange) {
let label: number | '...';
const pageNumber = calculatePageNumber(i, currentPage, paginationRange, totalPages);
const openingEllipsesNeeded = i === 2 && (isMiddle || isEnd);
const closingEllipsesNeeded = i === paginationRange - 1 && (isMiddle || isStart);
if (ellipsesNeeded && (openingEllipsesNeeded || closingEllipsesNeeded)) {
label = '...';
} else {
label = pageNumber;
}
pages.push(label);
i++;
}
return pages;
}
/**
* Given the position in the sequence of pagination links [i],
* figure out what page number corresponds to that position.
*
* Copied from 'ngx-pagination' package
*/
function calculatePageNumber(i: number, currentPage: number, paginationRange: number, totalPages: number) {
const halfWay = Math.ceil(paginationRange / 2);
if (i === paginationRange) {
return totalPages;
}
if (i === 1) {
return i;
}
if (paginationRange < totalPages) {
if (totalPages - halfWay < currentPage) {
return totalPages - paginationRange + i;
}
if (halfWay < currentPage) {
return currentPage - halfWay + i;
}
return i;
}
return i;
}
@Directive({
selector: 'ul[hlmPaginationContent]',
host: {
'data-slot': 'pagination-content',
},
})
export class HlmPaginationContent {
constructor() {
classes(() => 'flex flex-row items-center gap-1');
}
}
@Component({
selector: 'hlm-pagination-ellipsis',
imports: [HlmIconImports],
providers: [provideIcons({ lucideEllipsis })],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'data-slot': 'pagination-ellipsis',
},
template: `
<span aria-hidden="true">
<ng-icon hlm size="sm" name="lucideEllipsis" />
<span class="sr-only">{{ srOnlyText() }}</span>
</span>
`,
})
export class HlmPaginationEllipsis {
constructor() {
classes(() => 'flex size-9 items-center justify-center');
}
/** Screen reader only text for the ellipsis */
public readonly srOnlyText = input<string>('More pages');
}
@Directive({
selector: 'li[hlmPaginationItem]',
host: {
'data-slot': 'pagination-item',
},
})
export class HlmPaginationItem {
constructor() {
classes(() => '');
}
}
@Directive({
selector: '[hlmPaginationLink]',
hostDirectives: [
{
directive: RouterLink,
inputs: [
'target',
'queryParams',
'fragment',
'queryParamsHandling',
'state',
'info',
'relativeTo',
'preserveFragment',
'skipLocationChange',
'replaceUrl',
'routerLink: link',
],
},
],
host: {
'data-slot': 'pagination-link',
'[attr.data-active]': 'isActive() ? "true" : null',
'[attr.aria-current]': 'isActive() ? "page" : null',
},
})
export class HlmPaginationLink {
/** Whether the link is active (i.e., the current page). */
public readonly isActive = input<boolean, BooleanInput>(false, { transform: booleanAttribute });
/** The size of the button. */
public readonly size = input<ButtonVariants['size']>('icon');
/** The link to navigate to the page. */
public readonly link = input<RouterLink['routerLink']>();
constructor() {
classes(() => [
this.link() === undefined ? 'cursor-pointer' : '',
buttonVariants({
variant: this.isActive() ? 'outline' : 'ghost',
size: this.size(),
}),
]);
}
}
@Component({
selector: 'hlm-pagination-next',
imports: [HlmPaginationLink, NgIcon, HlmIcon],
providers: [provideIcons({ lucideChevronRight })],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<a
hlmPaginationLink
[link]="link()"
[queryParams]="queryParams()"
[queryParamsHandling]="queryParamsHandling()"
[size]="_size()"
[attr.aria-label]="ariaLabel()"
>
<span [class]="_labelClass()">{{ text() }}</span>
<ng-icon hlm size="sm" name="lucideChevronRight" />
</a>
`,
})
export class HlmPaginationNext {
constructor() {
classes(() => ['gap-1 px-2.5', !this.iconOnly() ? 'sm:pr-2.5' : '']);
}
/** The link to navigate to the next page. */
public readonly link = input<RouterLink['routerLink']>();
/** The query parameters to pass to the next page. */
public readonly queryParams = input<RouterLink['queryParams']>();
/** How to handle query parameters when navigating to the next page. */
public readonly queryParamsHandling = input<RouterLink['queryParamsHandling']>();
/** The aria-label for the next page link. */
public readonly ariaLabel = input<string>('Go to next page', { alias: 'aria-label' });
/** The text to display for the next page link. */
public readonly text = input<string>('Next');
/** Whether the button should only display the icon. */
public readonly iconOnly = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
protected readonly _labelClass = computed(() => (this.iconOnly() ? 'sr-only' : 'hidden sm:block'));
protected readonly _size = computed<ButtonVariants['size']>(() => (this.iconOnly() ? 'icon' : 'default'));
}
@Component({
selector: 'hlm-pagination-previous',
imports: [HlmPaginationLink, NgIcon, HlmIcon],
providers: [provideIcons({ lucideChevronLeft })],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<a
hlmPaginationLink
[link]="link()"
[queryParams]="queryParams()"
[queryParamsHandling]="queryParamsHandling()"
[size]="_size()"
[attr.aria-label]="ariaLabel()"
>
<ng-icon hlm size="sm" name="lucideChevronLeft" />
<span [class]="_labelClass()">{{ text() }}</span>
</a>
`,
})
export class HlmPaginationPrevious {
/** The link to navigate to the previous page. */
public readonly link = input<RouterLink['routerLink']>();
/** The query parameters to pass to the previous page. */
public readonly queryParams = input<RouterLink['queryParams']>();
/** How to handle query parameters when navigating to the previous page. */
public readonly queryParamsHandling = input<RouterLink['queryParamsHandling']>();
/** The aria-label for the previous page link. */
public readonly ariaLabel = input<string>('Go to previous page', { alias: 'aria-label' });
/** The text to display for the previous page link. */
public readonly text = input<string>('Previous');
/** Whether the button should only display the icon. */
public readonly iconOnly = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
protected readonly _labelClass = computed(() => (this.iconOnly() ? 'sr-only' : 'hidden sm:block'));
protected readonly _size = computed<ButtonVariants['size']>(() => (this.iconOnly() ? 'icon' : 'default'));
constructor() {
classes(() => ['gap-1 px-2.5', !this.iconOnly() ? 'sm:pl-2.5' : '']);
}
}
@Directive({
selector: '[hlmPagination],hlm-pagination',
host: {
'data-slot': 'pagination',
role: 'navigation',
'[attr.aria-label]': 'ariaLabel()',
},
})
export class HlmPagination {
/** The aria-label for the pagination component. */
public readonly ariaLabel = input<string>('pagination', { alias: 'aria-label' });
constructor() {
classes(() => 'mx-auto flex w-full justify-center');
}
}
export const HlmPaginationImports = [
HlmPagination,
HlmPaginationContent,
HlmPaginationItem,
HlmPaginationLink,
HlmPaginationPrevious,
HlmPaginationNext,
HlmPaginationEllipsis,
HlmNumberedPagination,
HlmNumberedPaginationQueryParams,
] as const;Usage
import { HlmPaginationImports } from '@spartan-ng/helm/pagination';<nav hlmPagination>
<ul hlmPaginationContent>
<li hlmPaginationItem>
<hlm-pagination-previous link="/components/menubar" />
</li>
<li hlmPaginationItem>
<a hlmPaginationLink link="#">1</a>
</li>
<li hlmPaginationItem>
<a hlmPaginationLink link="#" isActive>2</a>
</li>
<li hlmPaginationItem>
<a hlmPaginationLink link="#">3</a>
</li>
<li hlmPaginationItem>
<hlm-pagination-ellipsis />
</li>
<li hlmPaginationItem>
<hlm-pagination-next link="/components/popover" />
</li>
</ul>
</nav>Examples
Query Params
import { Component, computed, inject, numberAttribute } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { ActivatedRoute } from '@angular/router';
import { HlmPaginationImports } from '@spartan-ng/helm/pagination';
import { map } from 'rxjs/operators';
@Component({
selector: 'spartan-pagination-query-params',
imports: [HlmPaginationImports],
template: `
<nav hlmPagination>
<ul hlmPaginationContent>
@if (currentPage() > 1) {
<li hlmPaginationItem>
<hlm-pagination-previous link="." [queryParams]="{ page: currentPage() - 1 }" queryParamsHandling="merge" />
</li>
}
@for (page of pages; track 'page_' + page) {
<li hlmPaginationItem>
<a
hlmPaginationLink
[link]="currentPage() !== page ? '.' : undefined"
[queryParams]="{ page }"
queryParamsHandling="merge"
[isActive]="currentPage() === page"
>
{{ page }}
</a>
</li>
}
@if (currentPage() < pages[pages.length - 1]) {
<li hlmPaginationItem>
<hlm-pagination-next link="." [queryParams]="{ page: currentPage() + 1 }" queryParamsHandling="merge" />
</li>
}
</ul>
</nav>
`,
})
export class PaginationQueryParams {
private readonly _route = inject(ActivatedRoute);
/**
* Alternative would be to enable `withComponentInputBinding` in `provideRouter`.
* Than you can bind `input` signal to the query param.
*
* ```ts
* pageQuery = input<number, NumberInput>(1, {
* alias: 'page',
* transform: (value) => numberAttribute(value, 1),
* });
* ```
*
* This can replace `_pageQuery` and `currentPage` computed property.
*/
private readonly _pageQuery = toSignal(
this._route.queryParamMap.pipe(
map((params) => {
const pageQuery = params.get('page');
return pageQuery ? numberAttribute(pageQuery, 1) : undefined;
}),
),
);
public readonly currentPage = computed(() => this._pageQuery() ?? 1);
public pages = [1, 2, 3, 4];
}Icon Only (Previous/Next)
import { Component } from '@angular/core';
import { HlmPaginationImports } from '@spartan-ng/helm/pagination';
@Component({
selector: 'spartan-pagination-icon-only',
imports: [HlmPaginationImports],
template: `
<nav hlmPagination>
<ul hlmPaginationContent>
<li hlmPaginationItem>
<hlm-pagination-previous iconOnly="true" link="/components/menubar" />
</li>
<li hlmPaginationItem>
<a hlmPaginationLink link="#">1</a>
</li>
<li hlmPaginationItem>
<a hlmPaginationLink link="#" isActive>2</a>
</li>
<li hlmPaginationItem>
<a hlmPaginationLink link="#">3</a>
</li>
<li hlmPaginationItem>
<hlm-pagination-ellipsis />
</li>
<li hlmPaginationItem>
<hlm-pagination-next iconOnly="true" link="/components/popover" />
</li>
</ul>
</nav>
`,
})
export class PaginationIconOnly {}Advanced Pagination
100 total items | 10 pages
import { Component, signal } from '@angular/core';
import { HlmNumberedPagination } from '@spartan-ng/helm/pagination';
@Component({
selector: 'spartan-pagination-advanced',
imports: [HlmNumberedPagination],
template: `
<hlm-numbered-pagination [(currentPage)]="page" [(itemsPerPage)]="pageSize" [totalItems]="totalProducts()" />
`,
})
export class PaginationAdvanced {
public readonly page = signal(1);
public readonly pageSize = signal(10);
public readonly totalProducts = signal(100);
}Advanced Pagination - Query Params
Use hlm-numbered-pagination-query-params instead of hlm-numbered-pagination to synchronize pagination state with query params.
100 total items | 10 pages
import { Component, computed, inject, numberAttribute, signal } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { ActivatedRoute } from '@angular/router';
import { HlmNumberedPaginationQueryParams } from '@spartan-ng/helm/pagination';
import { map } from 'rxjs/operators';
@Component({
selector: 'spartan-pagination-advanced-query-params',
imports: [HlmNumberedPaginationQueryParams],
template: `
<hlm-numbered-pagination-query-params
[currentPage]="page()"
[(itemsPerPage)]="pageSize"
[totalItems]="totalProducts()"
/>
`,
})
export class PaginationAdvancedQuery {
private readonly _route = inject(ActivatedRoute);
/**
* Alternative would be to enable `withComponentInputBinding` in `provideRouter`.
* Than you can bind `input` signal to the query param.
*
* ```ts
* pageQuery = input<number, NumberInput>(1, {
* alias: 'page',
* transform: (value) => numberAttribute(value, 1),
* });
* ```
*
* This can replace `_pageQuery` and `page` computed property.
*/
private readonly _pageQuery = toSignal(
this._route.queryParamMap.pipe(
map((params) => {
const pageQuery = params.get('page');
return pageQuery ? numberAttribute(pageQuery, 1) : undefined;
}),
),
);
public readonly page = computed(() => this._pageQuery() ?? 1);
public readonly pageSize = signal(10);
public readonly totalProducts = signal(100);
}Helm API
HlmNumberedPaginationQueryParams
Selector: hlm-numbered-pagination-query-params
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| totalItems* (required) | number | - | The total number of items in the collection. Only useful when doing server-side paging, where the collection size is limited to a single page returned by the server API. |
| link | string | . | The URL path to use for the pagination links. Defaults to '.' (current path). |
| maxSize | number | 7 | The number of page links to show. |
| showEdges | boolean | true | Show the first and last page buttons. |
| pageSizes | number[] | [10, 20, 50, 100] | The page sizes to show. Defaults to [10, 20, 50, 100] |
HlmNumberedPagination
Selector: hlm-numbered-pagination
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| totalItems* (required) | number | - | The total number of items in the collection. Only useful when doing server-side paging, where the collection size is limited to a single page returned by the server API. |
| maxSize | number | 7 | The number of page links to show. |
| showEdges | boolean | true | Show the first and last page buttons. |
| pageSizes | number[] | [10, 20, 50, 100] | The page sizes to show. Defaults to [10, 20, 50, 100] |
HlmPaginationContent
Selector: ul[hlmPaginationContent]
HlmPaginationEllipsis
Selector: hlm-pagination-ellipsis
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| srOnlyText | string | More pages | Screen reader only text for the ellipsis |
HlmPaginationItem
Selector: li[hlmPaginationItem]
HlmPaginationLink
Selector: [hlmPaginationLink]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| isActive | boolean | false | Whether the link is active (i.e., the current page). |
| size | ButtonVariants['size'] | icon | The size of the button. |
| link | RouterLink['routerLink'] | - | The link to navigate to the page. |
HlmPaginationNext
Selector: hlm-pagination-next
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| link | RouterLink['routerLink'] | - | The link to navigate to the next page. |
| queryParams | RouterLink['queryParams'] | - | The query parameters to pass to the next page. |
| queryParamsHandling | RouterLink['queryParamsHandling'] | - | How to handle query parameters when navigating to the next page. |
| aria-label | string | Go to next page | The aria-label for the next page link. |
| text | string | Next | The text to display for the next page link. |
| iconOnly | boolean | false | Whether the button should only display the icon. |
HlmPaginationPrevious
Selector: hlm-pagination-previous
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| link | RouterLink['routerLink'] | - | The link to navigate to the previous page. |
| queryParams | RouterLink['queryParams'] | - | The query parameters to pass to the previous page. |
| queryParamsHandling | RouterLink['queryParamsHandling'] | - | How to handle query parameters when navigating to the previous page. |
| aria-label | string | Go to previous page | The aria-label for the previous page link. |
| text | string | Previous | The text to display for the previous page link. |
| iconOnly | boolean | false | Whether the button should only display the icon. |
HlmPagination
Selector: [hlmPagination],hlm-pagination
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| aria-label | string | pagination | The aria-label for the pagination component. |
On This Page
Stop configuring. Start shipping.
Zerops powers spartan.ng and Angular teams worldwide.
One-command deployment. Zero infrastructure headaches.
Deploy with Zerops