12. CDK Overlay & Portal

How Angular positions tooltips, dialogs, menus, and every floating element

Every dropdown menu, tooltip, dialog, and autocomplete panel in Angular Material is built on two CDK primitives: Overlay and Portal. The Overlay creates a floating layer above the page. The Portal projects content into it. Together, they solve a surprisingly hard problem: rendering content that escapes the normal DOM flow while staying correctly positioned, stacked, and accessible.

The Problem: Overflow and Stacking

Imagine a dropdown inside a div with overflow: hidden. In normal DOM flow, the dropdown's content is clipped:

<div style="overflow: hidden; height: 200px;">
  <button>Open Menu</button>
  <!-- This dropdown is CLIPPED by the overflow container -->
  <div class="dropdown" style="position: absolute; top: 40px;">
    <div>Option 1</div>
    <div>Option 2</div>
    <div>Option 3</div>
  </div>
</div>

Even with position: absolute or position: fixed, the dropdown fights against parent stacking contexts, z-index battles, and overflow clipping. This is a fundamental DOM limitation.

The CDK Overlay solves it by rendering the floating content in a separate container at the end of <body>, completely outside the component's DOM tree. It then positions it to appear connected to the trigger element.

Overlay: content escapes the component tree Component DOM tree div (overflow: hidden) height: 200px Button dropdown would be clipped here portal Overlay container (end of body) Dropdown Panel Option 1 Option 2 Option 3 Content is rendered outside the tree but positioned to appear attached

Portals: What to Render

A Portal is a piece of UI that can be dynamically attached to a host anywhere in the DOM. There are three types:

ComponentPortal

Renders a component class dynamically:

import { ComponentPortal } from '@angular/cdk/portal';

const portal = new ComponentPortal(TooltipComponent);

TemplatePortal

Renders a <ng-template> dynamically:

import { TemplatePortal } from '@angular/cdk/portal';

@Component({
  template: `
    <ng-template #myTemplate let-data="data">
      <div class="custom-content">
        <h3>{{ data.title }}</h3>
        <p>{{ data.body }}</p>
      </div>
    </ng-template>
  `
})
export class MyComponent {
  @ViewChild('myTemplate') template!: TemplateRef<any>;

  createPortal() {
    return new TemplatePortal(this.template, this.viewContainerRef, {
      data: { title: 'Hello', body: 'World' }
    });
  }
}

DomPortal

Renders an existing DOM element:

import { DomPortal } from '@angular/cdk/portal';

@Component({
  template: `<div #content>This element will be moved</div>`
})
export class MyComponent {
  @ViewChild('content') content!: ElementRef;

  createPortal() {
    return new DomPortal(this.content);
  }
}

Portal Outlet

You can render portals inline using cdkPortalOutlet:

<div class="sidebar">
  <ng-template [cdkPortalOutlet]="activePortal"></ng-template>
</div>

This is useful for rendering dynamic content in a fixed location — like a sidebar that changes based on the selected item.

Overlays: Where to Render

An Overlay creates a floating pane (a <div> appended to the overlay container at the end of <body>) and provides positioning, scrolling, and backdrop strategies.

Creating an overlay

import { Overlay, OverlayRef } from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';

@Component({ /* ... */ })
export class MenuTriggerComponent {
  private overlayRef: OverlayRef | null = null;

  constructor(
    private overlay: Overlay,
    private elementRef: ElementRef
  ) {}

  open() {
    // 1. Configure position, scroll, size
    const positionStrategy = this.overlay.position()
      .flexibleConnectedTo(this.elementRef)
      .withPositions([
        {
          originX: 'start',
          originY: 'bottom',
          overlayX: 'start',
          overlayY: 'top',
        }
      ]);

    // 2. Create the overlay
    this.overlayRef = this.overlay.create({
      positionStrategy,
      hasBackdrop: true,
      backdropClass: 'cdk-overlay-transparent-backdrop',
      scrollStrategy: this.overlay.scrollStrategies.reposition(),
    });

    // 3. Attach content via a Portal
    const portal = new ComponentPortal(DropdownMenuComponent);
    const componentRef = this.overlayRef.attach(portal);

    // 4. Handle close
    this.overlayRef.backdropClick().subscribe(() => this.close());
  }

  close() {
    this.overlayRef?.dispose();
    this.overlayRef = null;
  }
}

Position Strategies

The overlay needs to know where to appear. The CDK provides two strategies:

Connected Position (most common)

Positions the overlay relative to a trigger element. This is what tooltips, dropdowns, and autocompletes use.

const positionStrategy = this.overlay.position()
  .flexibleConnectedTo(triggerElement)
  .withPositions([
    // Primary: below the trigger, aligned to the left
    {
      originX: 'start',     // left edge of trigger
      originY: 'bottom',    // bottom edge of trigger
      overlayX: 'start',    // left edge of overlay
      overlayY: 'top',      // top edge of overlay
      offsetY: 4,           // 4px gap
    },
    // Fallback: above the trigger if no room below
    {
      originX: 'start',
      originY: 'top',
      overlayX: 'start',
      overlayY: 'bottom',
      offsetY: -4,
    },
    // Fallback: right-aligned if no room on the left
    {
      originX: 'end',
      originY: 'bottom',
      overlayX: 'end',
      overlayY: 'top',
      offsetY: 4,
    },
  ])
  .withFlexibleDimensions(true)
  .withPush(true)           // push into viewport if it overflows
  .withViewportMargin(8);   // 8px margin from viewport edges

The CDK tries each position in order, picking the first one that fits within the viewport. If none fit, it uses the first position and pushes the overlay into the viewport.

Connected positioning: preferred + fallback positions Preferred: below Trigger Overlay Fallback: above (no room below) Trigger Overlay viewport edge Fallback: right-aligned Trigger Overlay CDK tries each position in order until one fits the viewport withPush(true) nudges the overlay if nothing fits perfectly

Global Position

Positions the overlay relative to the viewport — used for dialogs, snackbars, and full-screen overlays:

const positionStrategy = this.overlay.position()
  .global()
  .centerHorizontally()
  .centerVertically();

// Or for a bottom-right snackbar:
const snackbarPosition = this.overlay.position()
  .global()
  .right('16px')
  .bottom('16px');

Scroll Strategies

What happens to the overlay when the user scrolls the page?

// Reposition: overlay moves with the trigger
scrollStrategy: this.overlay.scrollStrategies.reposition()

// Close: overlay closes on scroll
scrollStrategy: this.overlay.scrollStrategies.close()

// Block: prevent scrolling while overlay is open
scrollStrategy: this.overlay.scrollStrategies.block()

// Noop: do nothing (overlay stays in place)
scrollStrategy: this.overlay.scrollStrategies.noop()
Strategy Use case
reposition() Dropdowns, autocomplete, tooltips
close() Context menus, popovers
block() Dialogs, modals
noop() Fixed-position overlays, notifications

Backdrop

A backdrop is a click-catching layer behind the overlay. It can be transparent (for dropdowns) or visible (for dialogs):

this.overlay.create({
  hasBackdrop: true,
  backdropClass: 'cdk-overlay-dark-backdrop',  // semi-transparent black
  // or: 'cdk-overlay-transparent-backdrop'     // invisible click catcher
});

// React to backdrop clicks
overlayRef.backdropClick().subscribe(() => {
  overlayRef.dispose();
});

Custom backdrop styles

// A custom backdrop with a blur effect
.my-blur-backdrop {
  background: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(4px);
}
this.overlay.create({
  hasBackdrop: true,
  backdropClass: 'my-blur-backdrop',
});

Keyboard and Focus Management

Overlays should trap focus (for modals) or respond to Escape (for menus). The CDK provides tools for both:

Keyboard events

overlayRef.keydownEvents()
  .pipe(filter(e => e.key === 'Escape'))
  .subscribe(() => this.close());

Focus trapping

For modal overlays, use cdkTrapFocus to keep keyboard focus inside the overlay:

@Component({
  template: `
    <div cdkTrapFocus [cdkTrapFocusAutoCapture]="true">
      <h2>Dialog Title</h2>
      <p>Dialog content...</p>
      <button (click)="close()">Close</button>
    </div>
  `
})
export class DialogContentComponent {
  // Focus is trapped inside this component
  // Tab cycles between focusable elements
  // Focus returns to trigger when closed
}

Building a Custom Tooltip Directive

Here's a complete example that combines Overlay and Portal to build a reusable tooltip:

@Directive({
  selector: '[appTooltip]',
  standalone: true,
})
export class TooltipDirective implements OnDestroy {
  @Input('appTooltip') text = '';
  @Input() tooltipPosition: 'above' | 'below' | 'left' | 'right' = 'above';

  private overlayRef: OverlayRef | null = null;

  constructor(
    private overlay: Overlay,
    private elementRef: ElementRef,
    private viewContainerRef: ViewContainerRef
  ) {}

  @HostListener('mouseenter')
  show() {
    if (this.overlayRef) return;

    const positions = this.getPositions();

    const positionStrategy = this.overlay.position()
      .flexibleConnectedTo(this.elementRef)
      .withPositions(positions)
      .withPush(true)
      .withViewportMargin(8);

    this.overlayRef = this.overlay.create({
      positionStrategy,
      scrollStrategy: this.overlay.scrollStrategies.reposition(),
      panelClass: 'tooltip-panel',
    });

    const portal = new ComponentPortal(TooltipComponent, this.viewContainerRef);
    const ref = this.overlayRef.attach(portal);
    ref.instance.text = this.text;
  }

  @HostListener('mouseleave')
  hide() {
    this.overlayRef?.dispose();
    this.overlayRef = null;
  }

  private getPositions(): ConnectionPositionPair[] {
    switch (this.tooltipPosition) {
      case 'above':
        return [{
          originX: 'center', originY: 'top',
          overlayX: 'center', overlayY: 'bottom',
          offsetY: -8,
        }];
      case 'below':
        return [{
          originX: 'center', originY: 'bottom',
          overlayX: 'center', overlayY: 'top',
          offsetY: 8,
        }];
      case 'left':
        return [{
          originX: 'start', originY: 'center',
          overlayX: 'end', overlayY: 'center',
          offsetX: -8,
        }];
      case 'right':
        return [{
          originX: 'end', originY: 'center',
          overlayX: 'start', overlayY: 'center',
          offsetX: 8,
        }];
    }
  }

  ngOnDestroy() {
    this.overlayRef?.dispose();
  }
}

@Component({
  selector: 'app-tooltip',
  standalone: true,
  template: `<div class="tooltip-content">{{ text }}</div>`,
  styles: [`
    .tooltip-content {
      background: #333;
      color: white;
      padding: 6px 12px;
      border-radius: 4px;
      font-size: 13px;
      max-width: 200px;
    }
  `]
})
export class TooltipComponent {
  text = '';
}

Usage:

<button appTooltip="Save your changes" tooltipPosition="above">Save</button>
<span appTooltip="Click to copy" tooltipPosition="right">Copy link</span>

Building a Custom Dialog Service

A reusable dialog service that returns an Observable of the result:

@Injectable({ providedIn: 'root' })
export class DialogService {
  constructor(
    private overlay: Overlay,
    private injector: Injector
  ) {}

  open<T, R = any>(
    component: ComponentType<T>,
    config?: { data?: any; width?: string }
  ): DialogRef<R> {
    const positionStrategy = this.overlay.position()
      .global()
      .centerHorizontally()
      .centerVertically();

    const overlayRef = this.overlay.create({
      positionStrategy,
      hasBackdrop: true,
      backdropClass: 'cdk-overlay-dark-backdrop',
      scrollStrategy: this.overlay.scrollStrategies.block(),
      width: config?.width ?? '400px',
      maxWidth: '90vw',
      maxHeight: '90vh',
    });

    const dialogRef = new DialogRef<R>(overlayRef);

    const injector = Injector.create({
      parent: this.injector,
      providers: [
        { provide: DialogRef, useValue: dialogRef },
        { provide: DIALOG_DATA, useValue: config?.data },
      ],
    });

    const portal = new ComponentPortal(component, null, injector);
    overlayRef.attach(portal);

    // Close on backdrop click
    overlayRef.backdropClick().subscribe(() => dialogRef.close());

    // Close on Escape
    overlayRef.keydownEvents()
      .pipe(filter(e => e.key === 'Escape'))
      .subscribe(() => dialogRef.close());

    return dialogRef;
  }
}

export class DialogRef<R = any> {
  private afterClosed$ = new Subject<R | undefined>();

  constructor(private overlayRef: OverlayRef) {}

  close(result?: R) {
    this.overlayRef.dispose();
    this.afterClosed$.next(result);
    this.afterClosed$.complete();
  }

  afterClosed(): Observable<R | undefined> {
    return this.afterClosed$.asObservable();
  }
}

export const DIALOG_DATA = new InjectionToken<any>('DialogData');

Usage:

// Open a dialog
const ref = this.dialogService.open(ConfirmDialogComponent, {
  data: { title: 'Delete item?', message: 'This cannot be undone.' },
  width: '360px',
});

ref.afterClosed().subscribe(confirmed => {
  if (confirmed) this.deleteItem();
});

// In the dialog component:
@Component({
  template: `
    <h2>{{ data.title }}</h2>
    <p>{{ data.message }}</p>
    <div class="actions">
      <button (click)="dialogRef.close(false)">Cancel</button>
      <button (click)="dialogRef.close(true)" color="warn">Delete</button>
    </div>
  `
})
export class ConfirmDialogComponent {
  data = inject(DIALOG_DATA);
  dialogRef = inject(DialogRef);
}

This is essentially what MatDialog does under the hood — but now you understand every layer of the mechanism.

How Material Uses Overlay Internally

Every floating Material component is built on the same Overlay + Portal foundation:

Component Position strategy Scroll strategy Backdrop
mat-menu Connected (below trigger) Reposition Transparent
mat-autocomplete Connected (below input) Reposition None
mat-tooltip Connected (configurable) Reposition None
mat-dialog Global (centered) Block Dark
mat-snack-bar Global (bottom-center) Noop None
mat-select Connected (over trigger) Reposition Transparent
mat-datepicker Connected (below input) Reposition Transparent
mat-bottom-sheet Global (bottom) Block Dark

Understanding Overlay gives you the ability to customize or replace any of these behaviors, or build entirely new floating UI patterns.

Try It Yourself -- Overlay Position Explorer

Drag the trigger element around the canvas. The overlay repositions itself using the CDK's fallback position logic. Watch which position is selected as the trigger moves near viewport edges.

The Overlay Container

All overlays are rendered inside a single <div class="cdk-overlay-container"> at the end of <body>. This container holds:

  • Overlay panes — one <div class="cdk-overlay-pane"> per open overlay
  • Backdrops — one <div class="cdk-overlay-backdrop"> per overlay that requests one
  • Connected wrappers — positioning wrappers for connected overlays
<body>
  <app-root><!-- your app --></app-root>

  <!-- CDK Overlay Container -->
  <div class="cdk-overlay-container">
    <div class="cdk-overlay-backdrop cdk-overlay-dark-backdrop"></div>
    <div class="cdk-overlay-connected-position-bounding-box">
      <div class="cdk-overlay-pane" style="transform: translateX(120px) translateY(240px);">
        <!-- Your overlay content (portal) here -->
      </div>
    </div>
  </div>
</body>

Multiple overlays can be open simultaneously (e.g., a dialog with a tooltip inside it). They stack in DOM order, with later overlays appearing on top.

Summary

Concept Purpose
Portal Defines what to render (component, template, or DOM element)
Overlay Creates where to render it (floating pane outside the component tree)
Connected position Positions the overlay relative to a trigger element with fallback positions
Global position Positions the overlay relative to the viewport (centered, corner, etc.)
Scroll strategy Controls what happens on scroll (reposition, close, block, noop)
Backdrop Click-catching layer behind the overlay (transparent or visible)
Focus trap Keeps keyboard focus inside modal overlays

Overlay and Portal are the foundation of every floating element in Angular Material. Understanding them lets you build custom tooltips, dropdowns, context menus, dialogs, and notification systems — all with proper positioning, stacking, scroll handling, and accessibility baked in.

Series Recap

This series has taken you from raw RxJS streams to the Angular platform's most powerful building blocks:

  1. RxJS Observables — the reactive foundation
  2. Operators — transforming and controlling streams
  3. Combining Streams — coordinating multiple data sources
  4. Services & DI — encapsulating logic, sharing state
  5. Reactive Patterns — Subjects, async pipe, OnPush
  6. NgRx — predictable state management at scale
  7. Change Detection — how Angular decides what to re-render
  8. Signals — synchronous reactivity without Zone.js
  9. RxJS + Signals Bridge — when to use which, interop, migration
  10. Material Theming — design tokens, palettes, dark mode
  11. CDK Virtual Scrolling — rendering huge lists efficiently
  12. CDK Overlay & Portal — floating content, positioning, stacking

Each layer builds on the previous ones. The Overlay system uses Observables for scroll and keyboard events. Virtual scrolling leverages OnPush and change detection. Material Theming works with Signals for dynamic switching. It all connects.