Route Guards with canActivate and canDeactivate in Angular
📖 Scenario: You are building a simple Angular app with two pages: a Dashboard and a Profile. You want to protect the Dashboard so only logged-in users can access it. Also, when users try to leave the Profile page with unsaved changes, you want to warn them before they leave.
🎯 Goal: Build route guards using canActivate to protect the Dashboard route and canDeactivate to warn users about unsaved changes on the Profile page.
📋 What You'll Learn
Create a boolean variable
isLoggedIn to simulate user login statusCreate a
canActivate guard that allows navigation only if isLoggedIn is trueCreate a
canDeactivate guard that asks for confirmation if there are unsaved changesApply these guards to the Angular routes for Dashboard and Profile respectively
💡 Why This Matters
🌍 Real World
Route guards are used in real apps to protect pages from unauthorized access and prevent data loss by warning users before leaving pages with unsaved changes.
💼 Career
Understanding route guards is essential for Angular developers to build secure and user-friendly web applications.
Progress0 / 4 steps