CanActivate & CanDeactivate

Allow or Deny Navigation

CanActivate & CanDeactivate

Guards are functions that run before a route activates — or before the user leaves it — and decide whether navigation may proceed.

5 min read Level 3/5 #angular#router#guards
What you'll learn
  • Write a functional CanActivateFn
  • Block routes when the user is not authed
  • Use CanDeactivate for unsaved-changes warnings

A guard is a function the router calls before activating or deactivating a route. It returns a boolean, a UrlTree (to redirect), or a Promise / Observable of either.

A functional auth guard

Modern Angular prefers functional guards over class-based ones. Use inject() for dependencies.

import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';

export const authGuard: CanActivateFn = () => {
  const auth = inject(AuthService);
  const router = inject(Router);

  if (auth.loggedIn()) return true;
  return router.createUrlTree(['/login']);
};

Attach to a route

export const routes: Routes = [
  {
    path: 'app',
    component: AppShellComponent,
    canActivate: [authGuard],
  },
];

Multiple guards run in order — if any returns false (or a UrlTree), navigation is canceled.

CanDeactivate — unsaved changes

CanDeactivate is the inverse: run before leaving a route. It receives the component instance.

import { CanDeactivateFn } from '@angular/router';
import { EditorComponent } from './editor.component';

export const unsavedGuard: CanDeactivateFn<EditorComponent> = (cmp) => {
  return cmp.isDirty() ? confirm('Discard unsaved changes?') : true;
};
{ path: 'edit', component: EditorComponent, canDeactivate: [unsavedGuard] }

Other guards exist (canMatch, canActivateChild, canLoad) but canActivate and canDeactivate cover most cases.

Data Resolvers →