How does the CDK Overlay service help you build components like tooltips and dropdown menus that need to appear above everything else?
Short answer
The Overlay service creates a floating container attached to the page independent of the normal component layout, letting you position content precisely relative to a trigger element, and it handles things like closing when the user clicks outside or scrolls away, which would…
Advertisement
AModel answer
The Overlay service creates a floating container attached to the page independent of the normal component layout, letting you position content precisely relative to a trigger element, and it handles things like closing when the user clicks outside or scrolls away, which would otherwise be complex to build correctly from scratch.
import { Overlay, OverlayRef } from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';
constructor(private overlay: Overlay) {}
openTooltip() {
const overlayRef = this.overlay.create();
overlayRef.attach(new ComponentPortal(TooltipComponent));
}Real-world example
A data table shows a tooltip that always appears correctly above a specific column header, no matter where the table is scrolled to, thanks to the CDK Overlay service handling positioning and scroll tracking automatically.
Likely follow-ups
- How does the Overlay service decide where exactly to position the floating content?
- What happens to an overlay if the page is resized while it is open?
Related topics