Difference Between CanActivate and CanDeactivate in Angular

πŸ’‘ Concept Name

CanActivate vs CanDeactivate – Route guards in Angular used to control navigation access. CanActivate checks permission to enter a route, while CanDeactivate confirms before leaving a route.

πŸ“˜ Quick Intro

Angular uses route guards to control access to routes. CanActivate prevents users from accessing a route unless certain conditions are met. CanDeactivate ensures users can safely leave a component (e.g., warn if a form is unsaved).

🧠 Analogy / Short Story

Imagine a museum: CanActivate is like a security check at the entranceβ€”only those with tickets can enter. CanDeactivate is like a reminder at the exitβ€”"Are you sure you want to leave without saving your photo?"

πŸ”§ Technical Explanation

  • πŸ” CanActivate: Interface to check if navigation to a route should proceed.
  • πŸ”„ CanDeactivate: Interface to determine if it's safe to leave the current route/component.
  • πŸ“„ Implemented as services returning boolean | Observable<boolean> | Promise<boolean>.
  • 🧱 Used in Route configuration in AppRoutingModule.
  • ⚠️ Commonly used for auth, unsaved form prompts, confirmation dialogs.

🎯 Purpose & Use Case

  • βœ… Use CanActivate to restrict access to admin/user-only routes.
  • βœ… Use CanDeactivate to warn users about unsaved changes.
  • βœ… Improve UX by protecting navigation flow with guard logic.

πŸ’» Real Code Example

// CanActivate Example (auth.guard.ts)
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';

                    @Injectable(({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  constructor(private router: Router) { }

  canActivate(): boolean {
    const loggedIn = true; // Simulated condition
    if (!loggedIn) {
      this.router.navigate(['/login']);
      return false;
    }
    return true;
  }
}

// CanDeactivate Example (unsaved.guard.ts)
export interface CanComponentDeactivate {
  canDeactivate: () => boolean;
}

                    @Injectable(({ providedIn: 'root' })
export class UnsavedChangesGuard implements CanDeactivate {
  canDeactivate(component: CanComponentDeactivate): boolean {
    return component.canDeactivate ? component.canDeactivate() : true;
  }
}

❓ Interview Q&A

Q1: What is CanActivate used for?
A: It determines whether a user can access a specific route.

Q2: When do you use CanDeactivate?
A: When you want to confirm navigation away from a route (e.g., unsaved changes).

Q3: What does a route guard return?
A: A boolean, Promise<boolean>, or Observable<boolean>.

Q4: Can you use both guards on the same route?
A: Yes, you can combine multiple guards for comprehensive control.

Q5: Where are route guards defined?
A: In the route configuration within your routing module.

πŸ“ MCQs

Q1. What does CanActivate guard do?

  • Prevents editing
  • Blocks leaving
  • Prevents or allows entering a route
  • Loads components

Q2. What does CanDeactivate guard do?

  • Validates route data
  • Logs errors
  • Asks before leaving a route
  • Adds metadata

Q3. What is returned by route guards?

  • Number
  • Component
  • Boolean/Observable/Promise
  • Route

Q4. Where are route guards applied?

  • In app.module.ts
  • In component metadata
  • In route config
  • In ngOnInit

Q5. Which interface is used for unsaved changes?

  • CanActivate
  • CanExit
  • CanRoute
  • CanDeactivate

Q6. Which service helps secure protected routes?

  • FormBuilder
  • Resolver
  • AuthGuard
  • Router

Q7. Which Angular type is often guarded by CanDeactivate?

  • Home page
  • API Service
  • Form components
  • RouterModule

Q8. Which interface is needed to define CanDeactivate method?

  • CanAccess
  • CanComponentDeactivate
  • OnRouteExit
  • FormGuard

Q9. Can both CanActivate and CanDeactivate be used on same route?

  • No
  • Yes
  • Only on root
  • Only on lazy routes

Q10. What happens if a CanActivate guard returns false?

  • Redirects to 404
  • Route still loads
  • Navigation is cancelled
  • Returns to previous route

πŸ’‘ Bonus Insight

You can also use CanLoad for lazy-loaded modules, Resolve for fetching data before activation, and CanActivateChild for child route protection. Guards offer full navigation control in Angular.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

πŸ’¬ Feedback
πŸš€ Start Learning
Share:

Tags: