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

Walkthrough

Space play step click any line
Three takeaways
  1. 1A CanDeactivate guard returning an Observable<boolean> lets navigation wait on an async user decision.
  2. 2Functional guards can call inject() to pull services like MatDialog directly from the injection context.
  3. 3Pairing a route guard with a beforeunload listener covers both in-app and full browser-exit navigation.

Related explainers

typescript
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';

How a JWT strategy authenticates in NestJS

authentication jwt passport
Intermediate 7 steps
typescript
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { BehaviorSubject, Observable, throwError } from 'rxjs';
import { catchError, filter, take, switchMap } from 'rxjs/operators';

Refreshing auth tokens in an Angular interceptor

http-interceptor token-refresh rxjs
Advanced 8 steps
typescript
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';

How a GraphQL auth guard works in NestJS

authentication authorization jwt
Intermediate 7 steps
python
import os
from datetime import timedelta
 
 

Class-based config in a Flask app factory

configuration app-factory inheritance
Intermediate 7 steps
typescript
type ResizeCallback = (size: { width: number; height: number }) => void;
 
export function observeResize(callback: ResizeCallback, delay = 150) {
  let timeoutId: ReturnType<typeof setTimeout> | undefined;

Debouncing window resize in TypeScript

debounce closures event-listeners
Intermediate 6 steps
typescript
import { Injectable, Logger, OnApplicationShutdown } from '@nestjs/common';
import { InjectRedis } from '@nestjs-modules/ioredis';
import Redis from 'ioredis';
import { DataSource } from 'typeorm';

Graceful shutdown hooks in NestJS

graceful-shutdown lifecycle-hooks dependency-injection
Intermediate 7 steps

Share this explainer

Here's the card — post it anywhere.

Guarding navigation with CanDeactivate in Angular — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code