Bird
Raised Fist0
Angularframework~20 mins

Route guards (canActivate, canDeactivate) in Angular - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Angular Route Guard Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when canActivate guard returns false?
Consider an Angular route with a canActivate guard that returns false. What is the behavior when a user tries to navigate to this route?
AThe navigation proceeds and the route component loads normally.
BThe navigation is cancelled and the user stays on the current page.
CThe application throws a runtime error and crashes.
DThe router redirects automatically to the root path.
Attempts:
2 left
💡 Hint
Think about what a guard returning false means for navigation.
❓ state_output
intermediate
2:00remaining
What is the value of a flag after canDeactivate guard returns true?
In an Angular component, a canDeactivate guard checks a flag isSaved. If the guard returns true, what can we say about the isSaved flag after navigation away?
Angular
class EditComponent {
  isSaved = false;
  // canDeactivate guard checks this flag
}
AisSaved is false, meaning changes are not saved but navigation allowed.
BisSaved is true, meaning changes are saved before leaving.
CisSaved is undefined because the guard does not affect it.
DisSaved is reset to null automatically by Angular.
Attempts:
2 left
💡 Hint
The guard returning true means navigation is allowed, but does it guarantee saving?
📝 Syntax
advanced
2:30remaining
Which option correctly implements a canActivate guard returning an Observable?
Select the correct Angular canActivate guard method that returns an Observable allowing navigation only if a user is logged in.
Angular
import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { Observable, of } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  isLoggedIn = false;

  canActivate(): Observable<boolean> {
    // fill in correct return
  }
}
Areturn new Promise(resolve => resolve(this.isLoggedIn));
Breturn this.isLoggedIn ? true : false;
Creturn of(this.isLoggedIn);
Dreturn Observable.of(this.isLoggedIn);
Attempts:
2 left
💡 Hint
Use RxJS to return an Observable of a boolean value.
🔧 Debug
advanced
2:30remaining
Why does this canDeactivate guard cause a runtime error?
Given this canDeactivate guard code, why does it cause a runtime error when navigating away?
canDeactivate(component: any): boolean {
  return component.isSaved && component.hasPermission();
}
Angular
class EditComponent {
  isSaved = true;
  // hasPermission method is missing
}
AThe guard returns false always, blocking navigation.
Bcomponent.isSaved is undefined, causing a ReferenceError.
CThe guard returns a Promise instead of boolean, causing error.
Dcomponent.hasPermission is not a function, causing a TypeError.
Attempts:
2 left
💡 Hint
Check if all methods used on component exist.
🧠 Conceptual
expert
3:00remaining
What is the effect of returning a UrlTree from canActivate guard?
In Angular routing, if a canActivate guard returns a UrlTree instead of true or false, what happens?
AThe router cancels current navigation and redirects to the UrlTree path.
BThe router ignores the UrlTree and proceeds with navigation.
CThe router throws a syntax error because UrlTree is invalid return type.
DThe router navigates to both the original and UrlTree paths simultaneously.
Attempts:
2 left
💡 Hint
Think about how Angular handles redirect instructions from guards.

Practice

(1/5)
1. What is the primary purpose of the canActivate guard in Angular routing?
easy
A. To handle errors during route navigation.
B. To check if navigation to a route is allowed before entering it.
C. To preload data before the route loads.
D. To confirm if navigation away from a route is allowed.

Solution

  1. Step 1: Understand the role of canActivate

    canActivate is a route guard that runs before entering a route to decide if navigation is allowed.
  2. Step 2: Differentiate from other guards

    canDeactivate checks leaving a route, not entering. Preloading and error handling are unrelated to canActivate.
  3. Final Answer:

    To check if navigation to a route is allowed before entering it. -> Option B
  4. Quick Check:

    canActivate = check before entering route [OK]
Hint: canActivate controls entering routes, canDeactivate controls leaving [OK]
Common Mistakes:
  • Confusing canActivate with canDeactivate
  • Thinking canActivate preloads data
  • Assuming canActivate handles errors
2. Which of the following is the correct syntax to apply a canDeactivate guard to a route in Angular?
easy
A. { path: 'edit', component: EditComponent, canDeactivate: [UnsavedChangesGuard] }
B. { path: 'edit', component: EditComponent, canLoad: [LoadGuard] }
C. { path: 'edit', component: EditComponent, canActivate: [AuthGuard] }
D. { path: 'edit', component: EditComponent, canActivateChild: [ChildGuard] }

Solution

  1. Step 1: Identify the guard type for leaving routes

    canDeactivate is used to check if navigation away from a route is allowed.
  2. Step 2: Match syntax with canDeactivate

    The correct syntax uses canDeactivate: [GuardName] inside the route object.
  3. Final Answer:

    { path: 'edit', component: EditComponent, canDeactivate: [UnsavedChangesGuard] } -> Option A
  4. Quick Check:

    canDeactivate syntax = canDeactivate: [Guard] [OK]
Hint: Use canDeactivate: [Guard] to protect leaving a route [OK]
Common Mistakes:
  • Using canActivate instead of canDeactivate for leaving routes
  • Confusing canLoad with canDeactivate
  • Missing brackets around guard name
3. Given this canDeactivate guard code snippet, what will happen when the user tries to leave the EditComponent with unsaved changes?
export class UnsavedChangesGuard implements CanDeactivate<EditComponent> {
  canDeactivate(component: EditComponent): boolean {
    if (component.hasUnsavedChanges()) {
      return confirm('You have unsaved changes. Leave anyway?');
    }
    return true;
  }
}
medium
A. The guard throws an error because confirm is not allowed.
B. The user is always allowed to leave without confirmation.
C. The user is blocked from leaving if there are unsaved changes.
D. The user is asked to confirm leaving only if there are unsaved changes.

Solution

  1. Step 1: Analyze the guard logic

    The guard checks if component.hasUnsavedChanges() returns true, then asks for confirmation.
  2. Step 2: Understand the confirm behavior

    If the user confirms, confirm() returns true allowing navigation; otherwise, navigation is blocked.
  3. Final Answer:

    The user is asked to confirm leaving only if there are unsaved changes. -> Option D
  4. Quick Check:

    canDeactivate confirms only if unsaved changes exist [OK]
Hint: canDeactivate can prompt user to confirm leaving [OK]
Common Mistakes:
  • Assuming user can leave without confirmation always
  • Thinking guard blocks leaving without prompt
  • Believing confirm causes errors in Angular guards
4. Identify the error in this canActivate guard implementation:
export class AuthGuard implements CanActivate {
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (this.authService.isLoggedIn()) {
      return true;
    }
  }
}
medium
A. Missing return statement when user is not logged in.
B. Incorrect method name; should be canDeactivate.
C. The guard should return a Promise, not boolean.
D. The guard must not use services inside canActivate.

Solution

  1. Step 1: Check all code paths return a value

    If isLoggedIn() is false, the method returns nothing (undefined), which is invalid.
  2. Step 2: Understand guard return requirements

    canActivate must return true, false, or an observable/promise resolving to those. Missing return causes errors.
  3. Final Answer:

    Missing return statement when user is not logged in. -> Option A
  4. Quick Check:

    All canActivate paths must return true/false [OK]
Hint: Always return true or false in all canActivate paths [OK]
Common Mistakes:
  • Not returning false or redirect when unauthorized
  • Confusing canActivate with canDeactivate method names
  • Thinking services can't be used in guards
5. You want to prevent users from leaving a form page if they have unsaved changes, but only if they are editing (not creating new). Which approach correctly uses canDeactivate to achieve this?
hard
A. Use canActivate guard to check unsaved changes before entering the form route.
B. Use canDeactivate guard that always returns true to allow navigation.
C. Use canDeactivate guard that checks component.isEditing and component.hasUnsavedChanges() before confirming navigation.
D. Use canActivateChild guard to block leaving the form.

Solution

  1. Step 1: Identify when to block navigation away

    Blocking leaving only applies when editing and unsaved changes exist, so guard must check both conditions.
  2. Step 2: Use canDeactivate guard properly

    canDeactivate runs when leaving a route, so it is the correct place to check and confirm navigation.
  3. Final Answer:

    Use canDeactivate guard that checks component.isEditing and component.hasUnsavedChanges() before confirming navigation. -> Option C
  4. Quick Check:

    canDeactivate with condition on editing and unsaved changes [OK]
Hint: Check editing and unsaved changes inside canDeactivate guard [OK]
Common Mistakes:
  • Using canActivate to block leaving routes
  • Always returning true in canDeactivate guard
  • Confusing canActivateChild with canDeactivate
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard