BACK
Use casesDirty leave confirm — confirming before leaving a page
Use cases · 22

Dirty leave confirm — confirming before leaving a page

Pattern

The user has unsaved changes and tries to leave the page. We show a dialog: "You have unsaved changes. Leave?" If there are no changes, we let them go without asking.

The problem it solves

The dirty state changes over time — the user can touch and then revert the form. Read dirty ahead of time, or at the start of the session, and the guard uses a stale value. Also — if the user hits "back" several times, you need to cancel the old dialog and apply only the latest result.

Operators and why they matter

  • withLatestFrom(dirty$) — grabs the dirty state at the exact moment of the navigation attempt. A fresh value, not stale.
  • filter — pass on only if dirty=true. A clean form leaves without a dialog.
  • switchMap — a new navigation attempt cancels the old dialog. Only the last answer is applied.
  • map — turns the dialog boolean into an action: leave or stay.

Gotchas

  • mergeMap — two dialogs can open at once, and the SECOND result gets applied to the FIRST attempt. Chaos.
  • exhaustMap — ignores a new attempt until the user closes the previous dialog. Bad when the target URL changes.
  • Don't subscribe to dirty$ ahead of time or store the value in a variable — it can go stale by the time of the navigation attempt.

What you get

The confirmation appears exactly when needed, and decides the fate of the latest leave attempt. Unsaved changes are protected; a clean form doesn't get in the way.

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