typescript
52 lines · 7 steps
Guarding navigation with CanDeactivate in Angular
A functional route guard that asks users to confirm before leaving a page with unsaved form changes.
Explained by
highlit
1import { Injectable } from '@angular/core';
2import { CanDeactivateFn } from '@angular/router';
3import { inject } from '@angular/core';
4import { MatDialog } from '@angular/material/dialog';
5import { Observable, of } from 'rxjs';
6import { ConfirmDiscardDialogComponent } from './confirm-discard-dialog.component';
7
8export interface FormGuardComponent {
9 hasUnsavedChanges(): boolean;
10}
11
12export const canDeactivateForm: CanDeactivateFn<FormGuardComponent> = (
13 component,
14): Observable<boolean> | boolean => {
15 if (!component.hasUnsavedChanges()) {
16 return true;
17 }
18
19 const dialog = inject(MatDialog);
20
21 return dialog
22 .open(ConfirmDiscardDialogComponent, {
23 width: '420px',
24 data: {
25 title: 'Discard changes?',
26 message: 'You have unsaved changes that will be lost if you leave this page.',
27 confirmLabel: 'Discard',
28 cancelLabel: 'Keep editing',
29 },
30 })
31 .afterClosed();
32};
33
34@Injectable({ providedIn: 'root' })
35export class ProfileFormComponent implements FormGuardComponent {
36 private readonly form = inject(FormBuilder).group({
37 displayName: ['', Validators.required],
38 bio: [''],
39 });
40
41 hasUnsavedChanges(): boolean {
42 return this.form.dirty && !this.form.pristine;
43 }
44
45 @HostListener('window:beforeunload', ['$event'])
46 onBeforeUnload(event: BeforeUnloadEvent): void {
47 if (this.hasUnsavedChanges()) {
48 event.preventDefault();
49 event.returnValue = '';
50 }
51 }
52}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A CanDeactivate guard returning an Observable<boolean> lets navigation wait on an async user decision.
- 2Functional guards can call inject() to pull services like MatDialog directly from the injection context.
- 3Pairing a route guard with a beforeunload listener covers both in-app and full browser-exit navigation.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/guarding-navigation-with-candeactivate-in-angular-explained-typescript-136e/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.