skip to content

With the Angular CDK 22 overlay, how do you anchor a component to an element using createOverlayRef, a connected position strategy and a portal?

level: middleimportance: must knowfreq 42%

answer

  1. position, scroll, then content
  2. injector is the first argument
  3. withPositions on the origin element
  4. attach returns a ComponentRef
  5. keep the ref, dispose it

basics

~10 s

Build createFlexibleConnectedPositionStrategy(injector, cell).withPositions([...]), pass it as positionStrategy to createOverlayRef(injector, config), then attach a ComponentPortal of the editor. Keep the OverlayRef and call dispose() when you are done.

solid answer

~40 s

In Angular CDK 22 the functions from `@angular/cdk/overlay` take an `Injector` first. `createFlexibleConnectedPositionStrategy(injector, cellElement)` anchors to the cell, and `withPositions([...])` lists where the editor may sit, in order of preference. `createOverlayRef(injector, {positionStrategy, scrollStrategy, minWidth})` builds the floating host and returns an `OverlayRef` whose pane is empty. `ref.attach(new ComponentPortal(CellEditor, null, editorInjector))` creates the editor and returns its `ComponentRef`; the injector is how you hand it the cell value. The ref also gives you `keydownEvents()`, `outsidePointerEvents()` and `backdropClick()` to close it, and `dispose()` removes it for good. The older `inject(Overlay).create(config)` still works and calls the same code; the functions just let unused strategies be tree-shaken.

code

ts · 11 lines
ts
import {Component, inject, signal} from '@angular/core';
import {CELL_EDIT} from './sheet-grid';

@Component({
  selector: 'app-cell-editor',
  template: `<input [value]="draft()" (input)="draft.set($any($event.target).value)" />`,
})
export class CellEditor {
  private data = inject(CELL_EDIT);
  draft = signal(this.data.value);
}

go deeper

for a junior

Recall the order: build a position strategy, create the overlay ref with a config, attach a portal, and dispose the ref when the panel closes.

for a middle

Explain what each function receives, why the injector comes first, how a ComponentPortal finds its dependencies, and how detach differs from dispose.

for a senior

Show the lifecycle you would enforce: one overlay per edit, disposal on close and on destroy, explicit Escape and outside-click wiring, and setOrigin plus updatePosition when the anchor moves.

for a principal

Weigh the function API against the Overlay service for a shared library: smaller bundles and explicit injectors versus consistency with older code, and set one convention for the codebase.

## The pieces of a CDK overlay The Angular CDK overlay (`@angular/cdk/overlay`) floats content above the page. Opening one from code takes four decisions: 1. **Where** it sits: a *position strategy*. 2. **What happens on scroll**: a *scroll strategy*. 3. **How big** it is and whether it has a backdrop: the rest of `OverlayConfig`. 4. **What** it shows: a *portal* attached to the returned `OverlayRef`. Since Angular CDK 20, each piece has a standalone function that takes an `Injector` as its first argument: `createOverlayRef`, `createFlexibleConnectedPositionStrategy`, `createGlobalPositionStrategy`, and `createRepositionScrollStrategy`, `createBlockScrollStrategy`, `createCloseScrollStrategy`, `createNoopScrollStrategy`. The `Overlay` service with `overlay.create()`, `overlay.position()` and `overlay.scrollStrategies` remains and is not deprecated in 22.2.1; `Overlay.create` simply calls `createOverlayRef` with its own injector. Material's own menu trigger uses the function form. ## Anchoring a cell editor to the active cell In a spreadsheet-like grid, double-clicking a cell should open an editor that covers the cell and flips upward near the bottom edge: ```ts import {Component, InjectionToken, Injector, OnDestroy, inject} from '@angular/core'; import { OverlayRef, createOverlayRef, createFlexibleConnectedPositionStrategy, createRepositionScrollStrategy, } from '@angular/cdk/overlay'; import {ComponentPortal} from '@angular/cdk/portal'; import {CellEditor} from './cell-editor'; export const CELL_EDIT = new InjectionToken<{value: string}>('CELL_EDIT'); @Component({selector: 'app-sheet-grid', templateUrl: './sheet-grid.html'}) export class SheetGrid implements OnDestroy { private injector = inject(Injector); private editor: OverlayRef | null = null; openEditor(cell: HTMLElement, value: string) { this.closeEditor(); const positionStrategy = createFlexibleConnectedPositionStrategy(this.injector, cell) .withPositions([ {originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'top'}, {originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'bottom'}, ]); const ref = createOverlayRef(this.injector, { positionStrategy, scrollStrategy: createRepositionScrollStrategy(this.injector), minWidth: cell.offsetWidth, }); const editorInjector = Injector.create({ providers: [{provide: CELL_EDIT, useValue: {value}}], parent: this.injector, }); ref.attach(new ComponentPortal(CellEditor, null, editorInjector)); ref.keydownEvents().subscribe(e => e.key === 'Escape' && this.closeEditor()); this.editor = ref; } closeEditor() { this.editor?.dispose(); this.editor = null; } ngOnDestroy() { this.closeEditor(); } } ``` ## What each call does - `createFlexibleConnectedPositionStrategy(injector, origin)` accepts an `ElementRef`, an `Element`, or a point such as `{x, y}` for a context menu. `withPositions` takes `ConnectedPosition` objects, each naming a point on the origin (`originX`/`originY`) and the point on the overlay that meets it (`overlayX`/`overlayY`). The first position that fits wins. - `createOverlayRef(injector, config)` creates a host element with an inner **pane**, inserts it into the page, and returns an `OverlayRef`. Nothing is rendered in the pane yet. - `ref.attach(portal)` accepts a `ComponentPortal`, `TemplatePortal` or `DomPortal`. For a component it returns the `ComponentRef`; the position is recalculated after the content renders, because the size matters. - A `ComponentPortal` without its own injector resolves dependencies from the injector you gave `createOverlayRef`. Wrapping it with `Injector.create({providers, parent})`, as above, is the documented replacement for the removed `PortalInjector`. ## Other OverlayConfig fields - `width`, `height`, `minWidth`, `minHeight`, `maxWidth`, `maxHeight`: numbers mean pixels, strings pass through as CSS lengths; `overlayRef.updateSize()` changes them later. - `hasBackdrop` (default `false`) and `backdropClass` (default `cdk-overlay-dark-backdrop`; `cdk-overlay-transparent-backdrop` is the invisible variant). - `panelClass` adds classes to the pane, handy for theming one kind of overlay. - `direction` sets left-to-right or right-to-left; when omitted, it is taken from the injected `Directionality`. - `disposeOnNavigation` (default `false`) and `usePopover` (whether the host renders as a native popover). ## Closing and cleaning up The overlay does not close itself when built from code. The ref exposes streams you wire up: | Stream | Emits when | |---|---| | `keydownEvents()` | a key is pressed on the page and this is the most recently attached overlay with keydown subscribers | | `outsidePointerEvents()` | the user clicks outside the pane | | `backdropClick()` | the backdrop is clicked (only with `hasBackdrop: true`) | | `detachments()` | the content is detached | `detach()` removes the content but keeps the ref reusable; you can attach another portal later. `dispose()` is permanent: it disposes the position and scroll strategies, completes the streams and removes the host, and any later `attach` on that ref returns `null`. The grid above disposes on close and in `ngOnDestroy`, so navigating away never leaves an orphaned editor floating over the next page. `OverlayConfig` also has `disposeOnNavigation`, which defaults to `false`. ## Common mistakes - Reusing one strategy instance for two overlays throws in development mode; create one per overlay. - Forgetting `dispose()` leaves the host element and its subscriptions behind. - Passing no `scrollStrategy` means the noop default, so the editor stays put while the cell scrolls away.

  • The active cell moves with the arrow keys while the editor is open. How do you move the editor without recreating the overlay?
    Keep a reference to the `FlexibleConnectedPositionStrategy`, call `setOrigin(newCellElement)` on it, then `overlayRef.updatePosition()`, which re-runs the strategy's `apply()`. The ref, the attached editor and its state survive; only the anchor changes.
  • What does OverlayConfig's disposeOnNavigation accept in Angular CDK 22, and what is the default?
    It defaults to `false`, so the overlay ignores navigation. `true` or `'pop-state'` dispose it when the user presses the browser's back or forward button. `'url-change'`, added in 22.2.1, disposes it on any URL change, which the source warns can close overlays opened from route resolvers immediately.
  • When would you still inject the Overlay service instead of calling createOverlayRef?
    When existing code already uses it, or when you want `overlay.scrollStrategies` and `overlay.position()` as a convenience. Both paths create the same `OverlayRef`; `Overlay.create` calls `createOverlayRef` with the service's injector. The functions mainly help bundle size, because unused strategies are not pulled in.

  • An overlay built from code closes on Escape and outside clicks by itself.
  • detach() and dispose() are interchangeable ways to close an overlay.
  • createOverlayRef needs a ViewContainerRef to know where to render.
  • The Overlay service was removed when the create functions arrived.
  • One position strategy instance can be shared by several overlays.
  • Data reaches a portal component through PortalInjector.

Assumes Angular CDK 22; createOverlayRef and the create*Strategy functions arrived in 20 as tree-shakeable alternatives to the Overlay service, which still exists and is not deprecated.