Portal y Renderizado Overlay para Angular | ng-hub-ui-portal

Librería portal para Angular que permite renderizar componentes, plantillas y overlays fuera del árbol DOM actual con control de posicionamiento.

Última actualización 20 sept 2026

Visión General

Por qué los equipos buscan esta librería

Esta librería portal para Angular te ayuda a renderizar contenido en overlays o contenedores personalizados manteniendo predecibles el flujo de datos y la integración con Angular.

Instalación

npm install ng-hub-ui-portal

Ir a

Ideal para

  • drawers
  • paneles flotantes
  • interfaces overlay
  • contenedores dinámicos

Sobre portal

ng-hub-ui-portal es útil cuando las interfaces Angular necesitan desacoplar el renderizado del árbol DOM actual: drawers, paneles flotantes, contenedores dinámicos o UI basada en overlays. Da a los equipos una base más limpia para contenido proyectado y renderizado posicionado.

Guías de uso

Renderizado de contenido

Soporte para renderizar diversos tipos de contenido (Component, TemplateRef, String) con capacidades de inyección y proyección de datos.

Ejemplos:
Renderizado de componentes

Abre un portal con una clase de componente y accede a su instancia desde la referencia devuelta.

Código
Import:
Template:
Component:
Renderizado de TemplateRef

Renderiza un ng-template como contenido del portal, con close y dismiss disponibles en el contexto de la plantilla.

Código
Import:
Template:
Component:
Contenido de texto

Pasa una cadena de texto como contenido, para un portal que solo tiene una cosa que decir.

Código
Import:
Template:
Component:
Paso de datos

Entrega datos al componente de contenido mediante un Injector propio y recoge la respuesta en el valor de cierre.

Código
Import:
Template:
Component:

Estrategias de apertura

Controla cómo se abren los portales: modo progresivo (apilado) o exclusivo (toggle).

Ejemplos:
Apertura progresiva (apilada)

Apila portales con open(), cada uno encima del anterior, y consulta al servicio cuántos siguen abiertos.

Active Portals: 0
Código
Import:
Template:
Component:
Alternar (exclusivo)

toggle() descarta lo que hubiera abierto, espera a que se oculte y solo entonces muestra el nuevo portal.

Active Portal: None
Código
Import:
Template:
Component:

Contenedor de destino

Elige dónde se inserta la ventana del portal: el body del documento por defecto, o cualquier elemento indicado con un selector CSS o pasado como HTMLElement.

Ejemplos:
Contenedor personalizado (antiguo)

Envía la ventana a otro contenedor y vístela con windowClass. La colocación viene del CSS de esta demo: la librería inserta, no posiciona.

Configuración de Posicionamiento
Elementos de Referencia
Top LeftEsquina superior izquierda
Top RightEsquina superior derecha
CenterElemento central
Bottom LeftEsquina inferior izquierda
Bottom RightEsquina inferior derecha
Targets de Portal
Target 1
Target 2
Target 3
Configuración Actual
Posición: absolute
Target: body
Offset: X: 0px, Y: 0px
Backdrop: No
Código
Import:
Template:
Component:

Gestión de overlays

Mientras hay un portal abierto, la página de fondo deja de hacer scroll, el foco queda atrapado en la ventana superior y todo lo que queda fuera se marca con aria-hidden.

Ejemplos:
Uso básico (antiguo)

El uso corriente del servicio: abrir un portal, esperar su result y cerrarlo con un valor.

Portal Controls

Content is rendered dynamically into the DOM (typically body) using the HubPortal service, completely detaching it from this component's DOM hierarchy while preserving Angular context.

Código
Import:
Template:
Component:

Interacción

Cierra o descarta portales devolviendo resultados, con soporte de teclado y selectores de activación personalizados.

Ejemplos:
Proyección de contenido

Reparte el contenido en cabecera, cuerpo y pie con las opciones headerSelector y footerSelector.

Código
Import:
Template:
Component:
Renderizado de componentes

Abre un portal con una clase de componente y accede a su instancia desde la referencia devuelta.

Código
Import:
Template:
Component:

Ciclo de vida

Hooks de ciclo de vida y suscripciones a eventos para la gestión del estado del portal.

Ejemplos:
Servicio e inyección (antiguo)

Portales gobernados desde un servicio: toasts, diálogos y drawers, además de dismissAll, hasOpenPortals y activeInstances.

Gestión Programática de Portales
Notificaciones Toast
Modales Dinámicos
Overlays Complejos
Gestión Global
Estado del Sistema de Portales
Portales Activos:0
Último Portal:Ninguno
Z-Index Actual:1000
Auto-increment ID:1
Código
Import:
Template:
Component:
Apertura progresiva (apilada)

Apila portales con open(), cada uno encima del anterior, y consulta al servicio cuántos siguen abiertos.

Active Portals: 0
Código
Import:
Template:
Component:

Características clave

Cambios recientes

Version 22.2.2 - 9/20/26, 12:00 AM

changed: The npm keywords declare ng-hub-ui, the family name somebody searching for the ecosystem types. Metadata only: no code, types or styles change.

Version 22.2.1 - 9/16/26, 12:00 AM

changed: Repository, issue and README links follow the move to the hub-env organization. Issues for every Hub UI package are now gathered in hub-env/hub-ui, and the repository and bugs fields of the manifest point at the new addresses. No code, types or styles change.

Version 22.2.0 - 9/8/26, 12:00 AM

fixed: HubPortal.open() with a plain string opened an empty dialog. Every other kind of content is split into the three slots the window destructures, header, body and footer, but the string path returned a single slot: the text landed in the header and the body arrived undefined, which Angular projects as nothing, so the reader saw a blank box. The string now goes into the body slot like everything else, and four specs pin it. Worth stating plainly, because the same defect behaved worse in ng-hub-ui-modal, where it also took the keyboard down with it: here Escape never stopped working, because this window arms its listeners in ngOnInit rather than at the tail of the entry transition.

changed: The body mark is hub-portal-open. The old portal-open claimed a name in the application namespace rather than in the library one, the same defect ng-hub-ui-utils retired from the bare [tooltip] attribute in 22.14.0, and nothing warns a host whose own .portal-open rule is silently joined by ours. Both classes are written for now, so a stylesheet matching the old name keeps working; portal-open is removed in 23.0.0. See BREAKING_CHANGES.md.

changed: scrollable is delivered by the dialog rather than by a class on the content component host. That host is only a query root: its children are handed to the window and the host itself never enters the document, so component-host-scrollable, and the only rule this library shipped for it, matched nothing and asking for scrollable did nothing at all. The option now reaches the dialog through portal-dialog-scrollable, which the window already set, and the stylesheet dresses that class: the content box is pinned and the body scrolls inside it, or, where the content brings no .portal-body of its own, the content box is what scrolls.

changed: The slot split is one documented function instead of three inline expressions. Both declared slots are taken out of the container before the body is captured, and the body is captured as a static array. The old code read the body between the two extractions and got away with it only because what it captured was the live childNodes list, which Angular snapshots later, once both markers are already gone: correct by accident, disagreeing with the Node[][] ContentRef declares, and going empty the moment the nodes are projected out. No behaviour changes, and a spec now guards the contract.

added: Both READMEs state where this library stands on server-side rendering. The honest answer is not verified: a portal window only exists after a gesture, so the site prerender, which is the running proof for the libraries that render markup on the page, never draws one.

Version 22.1.0 - 9/6/26, 12:00 AM

changed: Dropped the angular16 keyword from the package manifest. The peer range has required Angular 18 or newer since 22.0.1, so the keyword was advertising the package to exactly the searchers whose install it would refuse.

changed: HubPortalRef is generic, so opening a portal no longer costs you the types. HubPortal.open<C, R>() and toggle<C, R>() infer C from the class handed to them, which is what makes componentInstance the component instead of any, while R types the value that travels through close(), result and closed. Until now the README answered this with a hand-written cast that claims a type nobody checks. Both parameters default to any, but componentInstance narrows from any to C | void, so a call site that reached straight through it stops compiling: see BREAKING_CHANGES.md. content is now typed Type<C> | TemplateRef<any> | string, which is what the stack already accepted, and the whole shape mirrors what ng-hub-ui-modal settled on in 22.5.0. Dismiss reasons stay untyped on purpose, because they carry either an internal PortalDismissReasons value or whatever the consumer passed.

removed: Removed the unused BACKDROP_ATTRIBUTES constant, a commented-out import in portal-config.ts and two commented-out lines of an older toggle() implementation. None of it was reachable, and backdropClass, the option that constant named, is not part of HubPortalOptions, so leaving it in suggested a backdrop API the library does not have. No behaviour changes.

fixed: Escape now dismisses the portal, as the keyboard option has always promised. The option was declared, defaulted to true in HubPortalConfig and documented in the README and on the docs site, but no key listener existed anywhere in the library: the close button was the only way out of a focus-trapped role=dialog, which left keyboard and screen-reader users stuck and forced every consumer to wire their own listener inside the projected component. The window now rejects its result promise with PortalDismissReasons.ESC, the reason the library exported without ever emitting it, honours keyboard: false per portal, steps aside when another handler has already consumed the key, and reacts only in the window holding focus, so a stack dismisses one dialog at a time from the top.

fixed: scrollable was declared a string on the portal window while HubPortalOptions declares it a boolean. Nothing misbehaved, because the template only tests the input for truthiness and the option reaches it through the name-based setInput, which no compiler ever checks, so the two had been free to disagree since the input was written. They now agree, which is what stops the next reader from believing the window and passing a string.

deprecated: HubPortalModule is deprecated and will be removed in 23.0.0. Its whole body is providers: [HubPortal], and HubPortal is providedIn: root, so importing the module never enabled the service; it only added a redundant second instance in whichever injector declared the import, delegating to the same root HubPortalStack and HubPortalConfig. Inject HubPortal and drop the import. The class carried no @deprecated tag until now, so neither an editor nor the build could warn anyone it was on its way out. See BREAKING_CHANGES.md.

Version 22.0.5 - 9/1/26, 12:00 AM

changed: The homepage in the manifest points at this library's own documentation page rather than at the site root. It is the link a registry shows beside the package and the one a reader clicks from it, and landing on a front page they then have to search is a worse answer than landing on the reference for the package they were already looking at. Metadata only — no code, no types, no styles change, and nothing a consumer imports is affected.

Version 22.0.4 - 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.0.3 - 7/28/26, 12:00 AM

fixed: Removed the invalid aria-portal attribute from the portal window host (not a real ARIA attribute); role=dialog and the aria-labelledby/describedby wiring stay.

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

fixed: Declared the real ng-hub-ui-utils peer range (>=22.0.0); the previous >=1.0.0 floor allowed resolving an incompatible utils major.

Version 22.0.1 - 6/26/26, 12:00 AM

fixed: Corrected the Angular peer dependency range to >=18.0.0. The library uses APIs introduced in Angular 17 (signal input()/output(), the @if control flow and signal queries), so the previous >=16.0.0 range let it install on versions it cannot run on.

fixed: Corrected the ng-hub-ui-utils peer range. The previous caret range resolved to >=1 <2, which excluded the current utils (22.x) and made the peer impossible to satisfy.

Version 22.0.0 - 6/17/26, 12:00 AM

changed: Aligned with Angular 22.

changed: README documentation standardized.

Version 0.3.4 - 6/14/26, 12:00 AM

fixed: Portal window options (animation, windowClass, portalDialogClass, …) are applied through ComponentRef.setInput instead of being assigned onto the instance. Since HubPortalWindow declares them as signal inputs, the direct assignment replaced the read-only signal function and threw TypeError: ctx.animation is not a function on every open().

fixed: Guarded parentNode when removing the window element during teardown, which threw when the element had already been detached.

Preguntas frecuentes

¿Para qué sirve ng-hub-ui-portal?

Para montar un componente, un TemplateRef o una simple cadena en otro sitio del DOM, desde código. Inyecta HubPortal, llama a open() y obtienes un HubPortalRef cuyo result es una promesa: se resuelve con lo que le pases a close() y se rechaza con el motivo que le des a dismiss(), y closed, dismissed, shown y hidden son sus equivalentes como observables. Dentro del contenido, inyecta HubActivePortal para cerrarlo desde dentro sin una referencia a quien lo abrió.

¿Cómo se elige dónde se monta el contenido?

La opción container acepta una cadena con un selector CSS o un HTMLElement, y por defecto es document.body. Se resuelve una sola vez, en el momento en que llamas a open(), así que el destino tiene que estar ya en el documento: si el selector no encuentra nada, la llamada lanza un error en vez de esperar. El contenido se añade al final de ese contenedor, y windowClass, portalDialogClass y portalContentClass son los enganches para tus propios estilos.

¿Qué diferencia hay entre portal y ng-hub-ui-modal?

ng-hub-ui-modal es el diálogo, con su backdrop, su apilado, sus tamaños y su colocación ya decididos. Portal es el mecanismo de montaje sin esa política: no dibuja backdrop ni aplica posicionamiento, así que el aspecto lo escribes tú. Lo que sí hace es envolver el contenido en su propia ventana con role=dialog, y sigue ocupándose de Escape mediante la opción keyboard, del foco al abrir y su restitución al cerrar, de beforeDismiss como guarda y de ocultar el resto de la página a las tecnologías de apoyo.

¿Se puede usar de forma declarativa en la plantilla, como el CDK de Angular?

No. No hay directiva ni outlet: la superficie pública es el servicio HubPortal, su referencia y el objeto de opciones. Dos consecuencias que conviene sopesar. Los inputs se ponen asignando sobre componentInstance, no con setInput, así que un componente construido con signal inputs no recibe los valores como esperarías. Y open() acude a document de inmediato, así que su sitio es el navegador: el renderizado en servidor no está verificado y la llamada necesita una guarda tuya.