BACK
Use casesClick outside — closing a popover
Use cases · 52

Click outside — closing a popover

Pattern

A popover, dropdown, or context menu should close on a click outside the component. A click inside (on content, buttons, an input) doesn't close it, or it'd be unusable.

The problem it solves

document.addEventListener('click', handler) in ngOnInit without an explicit removeEventListener in ngOnDestroy is a leak. The handler keeps firing after the component is destroyed, poking this.close() on null references, throwing errors.

Operators and why they matter

  • filter — the predicate checks that the click target is NOT inside the component's root element.
  • takeUntil(destroy$) — the listener dies with the component.
  • map — create a close event for the UI.

Gotchas

  • stopPropagation() on every nested element is an anti-pattern. One outside-click handler is cleaner.
  • Without takeUntil or takeUntilDestroyed the document listener lives forever — the classic leak.
  • If the popover renders through a portal (outside the component's DOM tree), a naive elementRef.nativeElement.contains won't work. You need a smarter check.

What you get

The popover closes only on an outside click, and the listener is guaranteed to be removed on destroy.

script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...