Библиотека утилит для Angular | ng-hub-ui-utils

Библиотека утилит для Angular с pipe, управлением фокусом, оверлеями, переходами и хелперами перевода, общими для переиспользуемых UI-компонентов.

Последнее обновление 26 авг. 2026 г.

Обзор

Почему команды ищут эту библиотеку

Используйте эту библиотеку утилит для Angular, чтобы не переписывать низкоуровневые части, стоящие за оверлеями, ловушками фокуса, хелперами перевода и распространёнными утилитами шаблонов.

Установка

npm install ng-hub-ui-utils

Перейти к

Идеально для

  • общая UI-инфраструктура
  • системы оверлеев
  • управление фокусом
  • хелперы шаблонов

О библиотеке utils

ng-hub-ui-utils — это общая основа за многими переиспользуемыми UI-паттернами. Она полезна, когда команды Angular хотят централизовать низкоуровневые части, которые поддерживают согласованность систем оверлеев, управления фокусом, pipe и хелперов перевода между проектами.

Руководства по возможностям

Управление фокусом

Захват и управление фокусом клавиатуры внутри элементов

Примеры:
Захват фокуса

Удерживайте фокус внутри модального окна или диалога с помощью hubFocusTrap().

Focus Trap Demo

Click "Enable Focus Trap" and try to Tab outside the blue box. Focus will stay trapped inside.

Focus Trap Area

Status: 🔓 Free

Focusable Elements

The selector FOCUSABLE_ELEMENTS_SELECTOR finds all focusable elements.

getFocusableBoundaryElements(container)→ [first, last] elements
Фокусируемые элементы

Получайте граничные фокусируемые элементы с помощью getFocusableBoundaryElements().

Focus Trap Demo

Click "Enable Focus Trap" and try to Tab outside the blue box. Focus will stay trapped inside.

Focus Trap Area

Status: 🔓 Free

Focusable Elements

The selector FOCUSABLE_ELEMENTS_SELECTOR finds all focusable elements.

getFocusableBoundaryElements(container)→ [first, last] elements

Интернационализация (i18n)

Сервисы и pipes перевода для поддержки нескольких языков

Примеры:
Сервис перевода

HubTranslationService для управления переводами

TranslatePipe - Basic usage

'welcome' | translate→ Welcome to ng-hub-ui

TranslatePipe - With parameters

'greeting' | translate:{ name: 'Carlos' }→ Hello, Carlos!

TranslatePipe - Nested keys

'buttons.save' | translate→ Save
'buttons.cancel' | translate→ Cancel

Programmatic access

translationService.getTranslation('buttons.delete')→ Delete
Pipe перевода

TranslatePipe для переводов в шаблонах

TranslatePipe - Basic usage

'welcome' | translate→ Welcome to ng-hub-ui

TranslatePipe - With parameters

'greeting' | translate:{ name: 'Carlos' }→ Hello, Carlos!

TranslatePipe - Nested keys

'buttons.save' | translate→ Save
'buttons.cancel' | translate→ Cancel

Programmatic access

translationService.getTranslation('buttons.delete')→ Delete
Провайдер перевода

provideHubTranslations() для настройки приложения

TranslatePipe - Basic usage

'welcome' | translate→ Welcome to ng-hub-ui

TranslatePipe - With parameters

'greeting' | translate:{ name: 'Carlos' }→ Hello, Carlos!

TranslatePipe - Nested keys

'buttons.save' | translate→ Save
'buttons.cancel' | translate→ Cancel

Programmatic access

translationService.getTranslation('buttons.delete')→ Delete
Внешний адаптер i18n

Настройте один реактивный мост переводов в app.config.ts для всех библиотек Hub UI.

Настройте один реактивный мост переводов в app.config.ts для всех библиотек Hub UI.

Код
Import:
Template:
Component:

Система оверлеев

Создание позиционированных overlays и плавающих элементов

Примеры:
Сервис overlay

HubOverlayService для программного создания overlay

A connected overlay positioned below the trigger, with a backdrop that closes it on outside click.

Ссылка на overlay

OverlayRef для управления жизненным циклом overlay

A connected overlay positioned below the trigger, with a backdrop that closes it on outside click.

Позиционирование

ConnectionPositionPair для гибкого позиционирования

A connected overlay positioned below the trigger, with a backdrop that closes it on outside click.

Сервис popup

Упрощённое управление popup

Примеры:
Создание popup

HubPopupService для быстрого создания popup

A connected overlay positioned below the trigger, with a backdrop that closes it on outside click.

Pipes

Вспомогательные pipes для шаблонов

Примеры:
Pipes для проверки типов

IsStringPipe, IsObjectPipe, IsObservablePipe

GetPipe - Access nested properties

user | get:'profile.name'→ John Doe
user | get:'profile.address.city'→ New York

IsStringPipe - Type checking

'Hello' | isString→ true
123 | isString→ false

IsObjectPipe - Object detection

{ a: 1 } | isObject→ true
'string' | isObject→ false

UcfirstPipe - Capitalize first letter

'hello world' | ucfirst→ Hello world
GetPipe

Доступ к вложенным свойствам объекта через точечную нотацию

GetPipe - Access nested properties

user | get:'profile.name'→ John Doe
user | get:'profile.address.city'→ New York

IsStringPipe - Type checking

'Hello' | isString→ true
123 | isString→ false

IsObjectPipe - Object detection

{ a: 1 } | isObject→ true
'string' | isObject→ false

UcfirstPipe - Capitalize first letter

'hello world' | ucfirst→ Hello world
UcfirstPipe

Перевод первой буквы строки в верхний регистр

GetPipe - Access nested properties

user | get:'profile.name'→ John Doe
user | get:'profile.address.city'→ New York

IsStringPipe - Type checking

'Hello' | isString→ true
123 | isString→ false

IsObjectPipe - Object detection

{ a: 1 } | isObject→ true
'string' | isObject→ false

UcfirstPipe - Capitalize first letter

'hello world' | ucfirst→ Hello world
UnwrapAsyncPipe

Разворачивание observables и promises в шаблонах

GetPipe - Access nested properties

user | get:'profile.name'→ John Doe
user | get:'profile.address.city'→ New York

IsStringPipe - Type checking

'Hello' | isString→ true
123 | isString→ false

IsObjectPipe - Object detection

{ a: 1 } | isObject→ true
'string' | isObject→ false

UcfirstPipe - Capitalize first letter

'hello world' | ucfirst→ Hello world

Вспомогательные функции

Вспомогательные функции общего назначения

Примеры:
Type guards

isString(), isNumber(), isDefined(), isPromise()

Type Guards

isString('hello')→ true
isNumber(42)→ true
isDefined(null)→ false
isDefined('value')→ true

Deep Equality

equals({a:1}, {a:1})→ true
equals([1,2], [1,2])→ true

Object Access

getValue(user, 'profile.name')→ John Doe

String Interpolation

interpolateString('Hello {{name}}', {name: 'World'})→ Hello World

String Utilities

removeAccents('Ñoño café')→ Nono cafe
padNumber(5)→ 05
Утилиты для строк

removeAccents(), interpolateString(), regExpEscape()

Type Guards

isString('hello')→ true
isNumber(42)→ true
isDefined(null)→ false
isDefined('value')→ true

Deep Equality

equals({a:1}, {a:1})→ true
equals([1,2], [1,2])→ true

Object Access

getValue(user, 'profile.name')→ John Doe

String Interpolation

interpolateString('Hello {{name}}', {name: 'World'})→ Hello World

String Utilities

removeAccents('Ñoño café')→ Nono cafe
padNumber(5)→ 05
Утилиты для объектов

equals() для глубокого сравнения, getValue() для точечной нотации

Type Guards

isString('hello')→ true
isNumber(42)→ true
isDefined(null)→ false
isDefined('value')→ true

Deep Equality

equals({a:1}, {a:1})→ true
equals([1,2], [1,2])→ true

Object Access

getValue(user, 'profile.name')→ John Doe

String Interpolation

interpolateString('Hello {{name}}', {name: 'World'})→ Hello World

String Utilities

removeAccents('Ñoño café')→ Nono cafe
padNumber(5)→ 05
Утилиты для DOM

closest(), reflow(), getActiveElement()

Type Guards

isString('hello')→ true
isNumber(42)→ true
isDefined(null)→ false
isDefined('value')→ true

Deep Equality

equals({a:1}, {a:1})→ true
equals([1,2], [1,2])→ true

Object Access

getValue(user, 'profile.name')→ John Doe

String Interpolation

interpolateString('Hello {{name}}', {name: 'World'})→ Hello World

String Utilities

removeAccents('Ñoño café')→ Nono cafe
padNumber(5)→ 05
Утилиты RxJS

Оператор runInZone() для интеграции с NgZone

Type Guards

isString('hello')→ true
isNumber(42)→ true
isDefined(null)→ false
isDefined('value')→ true

Deep Equality

equals({a:1}, {a:1})→ true
equals([1,2], [1,2])→ true

Object Access

getValue(user, 'profile.name')→ John Doe

String Interpolation

interpolateString('Hello {{name}}', {name: 'World'})→ Hello World

String Utilities

removeAccents('Ñoño café')→ Nono cafe
padNumber(5)→ 05

Утилиты для scrollbar

Измерение и компенсация ширины scrollbar

Примеры:
Ширина scrollbar

Функции scrollbarWidth() и scrollbarPadding()

ScrollBar Service

The ScrollBar service helps manage scrollbar visibility and compensate for layout shifts when hiding scrollbars (e.g., when opening modals).

Use Case: Modal Body Lock

When opening a modal, you typically hide the body scrollbar. The ScrollBar.hide() method handles this automatically and returns a reverter function.

Status: 🔓 Normal scrolling

Code Example

import { inject } from '@angular/core';
import { ScrollBar } from 'ng-hub-ui-utils';

export class ModalService {
  private scrollBar = inject(ScrollBar);
  private revertScrollbar: (() => void) | null = null;

  openModal() {
    // Hide scrollbar and get reverter function
    this.revertScrollbar = this.scrollBar.hide();
  }

  closeModal() {
    // Restore scrollbar
    if (this.revertScrollbar) {
      this.revertScrollbar();
      this.revertScrollbar = null;
    }
  }
}

Переходы

Хелперы для переходов CSS

Примеры:
Запуск перехода

hubRunTransition() для программных переходов CSS

Предпросмотр вживую для этого примера пока недоступен.

Подсказка

Лёгкие настраиваемые подсказки для любого элемента через директиву [tooltip].

Примеры:
Директива подсказки

Примените [tooltip] с указанием размещения, чтобы показывать позиционированную подпись при наведении или фокусе; оформляется переменными --hub-tooltip-*.

Placements (hover the buttons)
Themed with --hub-tooltip-* variables

Ключевые возможности

Последние изменения

Version 22.8.0 - 8/14/26, 12:00 AM

added: provideHubTranslationAdapter() — the application-wide reactive bridge from an external translation service (transloco, ngx-translate, i18next…) into HubTranslationService. Register it once at bootstrap and every ng-hub-ui library picks up the host dictionary, re-emitting on every language change. Supports optional namespacing and deliberate per-label reactive overrides.

added: HUB_TRANSLATION_PREFIX — injection token that scopes the lookups of a library to a collision-safe HUBUI.<LIBRARY>.* namespace. TranslatePipe resolves the prefixed key first and falls back to the bare key, so existing flat dictionaries keep working untouched.

Version 22.7.2 - 8/8/26, 12:00 AM

fixed: Documentation links now point at the canonical localized URLs. The README linked to https://hubui.dev/<path> with no locale prefix and no trailing slash, and both forms are 301-redirected, so every reader arriving from npm or GitHub landed on a redirect instead of the canonical page.

Version 22.7.1 - 7/27/26, 12:00 AM

fixed: --hub-overlay-zindex / --hub-overlay-backdrop-zindex actually work now: OverlayRef resolves its inline z-index through var(--hub-overlay-zindex, 1000) / var(--hub-overlay-backdrop-zindex, 999) instead of literal values, so re-stacking an overlay no longer requires !important. Defaults are unchanged.

added: OverlayConfig.zIndex — optional explicit layer for a single overlay instance; when set it takes precedence over the token.

Version 22.7.0 - 7/7/26, 12:00 AM

added: resolveHubAccent(value) — the canonical "any colour" accent resolver shared across the ng-hub-ui family: barewords map to var(--hub-sys-color-<name>, <name>), literal #hex / rgb() / oklch() / var() values pass through unchanged, empty values yield null.

Version 22.6.1 - 7/2/26, 12:00 AM

fixed: CSS variable fallbacks realigned to the ds light defaults (e.g. --hub-ref-font-family-base falls back to the system-ui stack instead of inherit); fallbacks only apply when ng-hub-ui-ds is not loaded.

Version 22.6.0 - 6/30/26, 12:00 AM

added: HubOverflowTooltipDirective ([hubOverflowTooltip]) — shows a tooltip only while the host label is actually truncated, with live tracking via ResizeObserver + MutationObserver.

added: Agnostic tooltip token — HUB_TOOLTIP_ADAPTER plus provideHubTooltip(adapter) let any tooltip implementation back [hubOverflowTooltip], app-wide or per subtree; defaults to the built-in hubTooltipAdapter.