NG.V · Angular 22 practice question
When implementing a `CanDeactivate` guard in Angular to prevent navigation away from a form that has unsaved changes, which pattern represents the correct approach to allow the user to proceed after confirmation, rather than just blocking navigation? Consider a functional guard:
export const unsavedChangesGuard: CanDeactivateFn<FormComponent> = (component) => {
// return boolean | Promise<boolean> | Observable<boolean> | UrlTree
};
Check answer and explanation
Correct answer: If unsaved changes exist, return a `Promise` or `Observable` that resolves to `true` only after the user confirms they wish to leave the page, ensuring the guard itself handles the confirmation logic.
Explanation
The purpose of a `CanDeactivate` guard is to signal to the router whether navigation should proceed (`true`) or be blocked (`false`). To allow the user to proceed *after* confirmation (a desired pattern for user experience), the guard must return a mechanism (like a Promise/Observable) that only resolves to `true` once the user has affirmatively chosen to leave, effectively letting the guard control the flow based on user interaction outside of simple boolean checks.
Common trap
Option C incorrectly suggests the guard blocks navigation (`false`) and then an external router call forces it, which is overly complex and bypasses the guard's primary role in deciding the initial navigation flow.
Source: Angular Routing Guide (Review specific guard usage documentation for modern Angular versions) - https://angular.dev/guide/routing
Checked against the cited text on 2026-11-27.