skip to content

In an Angular template, how do the CDK's cdkOverlayOrigin and cdkConnectedOverlay directives open a panel, and which defaults do they apply that createOverlayRef does not?

level: middleimportance: should knowfreq 38%

answer

  1. origin plus an ng-template
  2. the Open input drives attach
  3. dropdown positions by default
  4. reposition, not noop
  5. Escape closes, outside click only emits

basics

~20 s

Mark the trigger with cdkOverlayOrigin and put cdkConnectedOverlay on an ng-template whose Origin and Open inputs point at it. The directive adds dropdown positions, a reposition scroll strategy and Escape-to-close, defaults a code-built overlay lacks.

solid answer

~40 s

`cdkOverlayOrigin` on the header button exports a reference, and `cdkConnectedOverlay` on an `<ng-template>` takes it through `[cdkConnectedOverlayOrigin]`. When `[cdkConnectedOverlayOpen]` becomes true the directive creates an overlay with a flexible connected position strategy and attaches the template as a `TemplatePortal`; false detaches it, and destroying the directive disposes it. Unlike a bare `createOverlayRef` call, it falls back to four dropdown positions, uses the reposition scroll strategy instead of noop, and detaches itself on Escape unless `cdkConnectedOverlayDisableClose` is set. Outside clicks only emit `overlayOutsideClick` and backdrop clicks only emit `backdropClick`; you close the panel yourself. Because Escape closes it internally, listen to `(detach)` so your own open flag stays in sync.

code

ts · 13 lines
ts
import {Component, input, signal} from '@angular/core';
import {CdkConnectedOverlay, CdkOverlayOrigin} from '@angular/cdk/overlay';
import {ColumnFilter} from './column-filter';

@Component({
  selector: 'app-column-header',
  imports: [CdkOverlayOrigin, CdkConnectedOverlay, ColumnFilter],
  templateUrl: './column-header.html',
})
export class ColumnHeader {
  column = input.required<string>();
  filterOpen = signal(false);
}

go deeper

for a junior

Recall the pairing: cdkOverlayOrigin on the trigger, cdkConnectedOverlay on an ng-template, with the Origin and Open inputs connecting them.

for a middle

Explain how the Open input maps to attach and detach, which defaults differ from a bare overlay config, and why Escape needs the detach output to keep state in sync.

for a senior

Spot the production bugs: the double-click-to-reopen after Escape, panels overflowing because push is off, and app-wide scroll behaviour set through the scroll-strategy token.

for a principal

Decide when a team standardises on the directive versus code-built overlays, and set shared defaults through the default-config token instead of per-instance inputs.

## Two directives, one overlay The Angular CDK overlay can be driven entirely from a template with two standalone directives from `@angular/cdk/overlay` (also exported by `OverlayModule`): - **`cdkOverlayOrigin`** marks the element the panel is anchored to. It is exported as `cdkOverlayOrigin`, so `#filterBtn="cdkOverlayOrigin"` gives you a reference. - **`cdkConnectedOverlay`** sits on an `<ng-template>`. The template is the content; the directive wraps it in a `TemplatePortal` and owns the overlay that shows it. In a spreadsheet-like grid, each column header can carry a filter button that opens a panel of checkboxes: ```html <button type="button" cdkOverlayOrigin #filterBtn="cdkOverlayOrigin" (click)="filterOpen.set(!filterOpen())">Filter</button> <ng-template cdkConnectedOverlay [cdkConnectedOverlayOrigin]="filterBtn" [cdkConnectedOverlayOpen]="filterOpen()" (overlayOutsideClick)="filterOpen.set(false)" (detach)="filterOpen.set(false)"> <app-column-filter [column]="column()" /> </ng-template> ``` ## What the directive does with its inputs 1. The first time `cdkConnectedOverlayOpen` turns true, it calls `createOverlayRef` with a `createFlexibleConnectedPositionStrategy` anchored to the origin, then attaches its `TemplatePortal`. 2. When the input turns false, it detaches the overlay; the ref is kept for the next open. 3. When the directive is destroyed, for example because the header leaves the DOM, it disposes the overlay. 4. Changes to inputs such as positions, offsets, width or the origin are pushed into the existing strategy and overlay. Common inputs include `cdkConnectedOverlayPositions`, `cdkConnectedOverlayOffsetX`/`OffsetY`, `cdkConnectedOverlayWidth`/`Height`/`MinWidth`/`MinHeight`, `cdkConnectedOverlayPanelClass`, `cdkConnectedOverlayHasBackdrop`, `cdkConnectedOverlayBackdropClass`, `cdkConnectedOverlayScrollStrategy`, `cdkConnectedOverlayViewportMargin`, `cdkConnectedOverlayLockPosition` and `cdkConnectedOverlayPush`. A `CDK_CONNECTED_OVERLAY_DEFAULT_CONFIG` token can set defaults for every instance. ## Defaults compared with a code-built overlay | Concern | `cdkConnectedOverlay` | `createOverlayRef` with a bare config | |---|---|---| | Positions | four dropdown positions if none are given | you must call `withPositions` (at least one is required) | | Scroll strategy | reposition, from `CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY` | noop | | Escape | detaches unless `cdkConnectedOverlayDisableClose` is true | nothing until you subscribe to `keydownEvents()` | | Outside click | emits `overlayOutsideClick`, stays open | `outsidePointerEvents()` emits, stays open | | Backdrop | off; `backdropClick` emits when on | off; `backdropClick()` emits when on | | Push on-screen | off (`cdkConnectedOverlayPush` defaults to false) | on (the strategy's own default) | | Flexible dimensions | off | on | | Cleanup | disposed when the directive is destroyed | yours to call | The default positions are, in order: below the origin aligned to its start edge, above aligned to the start, above aligned to the end, and below aligned to the end. That is the classic dropdown flip. ## The two-way state trap The directive keeps its own `open` field. When the user presses Escape it detaches the overlay and sets that internal field to false, but it cannot change *your* signal. If nothing tells your component, `filterOpen()` is still true, so the next click on the header sets it to false, which the directive sees as "close an already closed panel", and only the second click reopens it. Two fixes: - listen to `(detach)`, which fires whenever the overlay content is detached, and reset your flag there, as the example does; - or set `cdkConnectedOverlayDisableClose` and handle Escape yourself through `(overlayKeydown)`. `overlayOutsideClick` deliberately skips clicks on the origin itself, so the toggle button above does not close and immediately reopen the panel. ## Directive or code? The directive is the better fit when the panel's content is markup that belongs to the template around it and its open state is a simple flag, as with a header's filter panel. Building the overlay in code is the better fit when: - the anchor changes at run time, as with a cell editor that follows the active cell; - the content is a component chosen by code, wrapped in a `ComponentPortal`; - the opening code needs the `OverlayRef` streams directly, for example to commit an edit on `detachments()`; - the overlay must outlive the template that would otherwise host the directive. Both paths end in the same `OverlayRef`, so behaviour such as positions and scroll strategies is shared knowledge. ## Other outputs worth knowing - `attach` and `detach` fire after the content is attached or detached. - `positionChange` emits a `ConnectedOverlayPositionChange` whenever the applied position changes; the directive only subscribes while you listen. - `overlayKeydown` emits keyboard events while the overlay is the topmost one listening. - The directive exposes its `overlayRef`, so you can call `updatePosition()` when the panel's content changes size.

  • How would you make every cdkConnectedOverlay in the grid close when the page scrolls instead of following its header?
    Either bind `[cdkConnectedOverlayScrollStrategy]` on each instance to a close strategy you create, or provide `CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY` with a factory that returns `() => createCloseScrollStrategy(injector)`, since the token holds a function that creates a fresh strategy per instance. The token is what supplies the reposition default, so overriding it changes every directive in that injector's scope.
  • Why do the filter panels near the right edge of the screen overflow instead of sliding back into view?
    The directive passes `cdkConnectedOverlayPush` as false by default, so when none of the positions fits, it applies the one with the most visible area and lets it overflow. Setting `cdkConnectedOverlayPush` to true lets the strategy push the panel back on-screen.

  • Clicking outside a cdkConnectedOverlay panel closes it by default.
  • The directive uses the noop scroll strategy, like a bare overlay config.
  • Escape-to-close updates the parent's bound open flag automatically.
  • cdkConnectedOverlay belongs on the trigger button, not on an ng-template.
  • The directive leaves the overlay alive after the component is destroyed.