Loading

Quipoin Menu

Learn • Practice • Grow

angular / Route Guards
interview

Q1. What are route guards in Angular?
Route guards are interfaces that control whether a route can be activated, deactivated, loaded, etc. They''re used for authentication, authorization, unsaved changes protection, or data fetching before navigation. Guards return boolean, Promise, or Observable.

Q2. What types of guards are available in Angular?
CanActivate (check if route can be activated), CanActivateChild (for child routes), CanDeactivate (prevent leaving a route), CanLoad (prevent lazy loading a module), Resolve (fetch data before route activation). Each has a corresponding interface to implement.

Q3. How do you implement a CanActivate guard?
Create a guard class implementing CanActivate. Example:
@Injectable({ providedIn: ''root'' }) export class AuthGuard implements CanActivate { canActivate(): boolean { return this.auth.isLoggedIn(); } }
Then add to route: { path: ''admin'', component: AdminComponent, canActivate: [AuthGuard] }.

Q4. What is a Resolve guard used for?
Resolve prefetches data before the route activates, ensuring data is available when the component loads. It returns an observable or promise. The resolved data is available via ActivatedRoute.data. Useful for avoiding flickering or conditional navigation.

Q5. How do you prevent navigation away from a form with unsaved changes?
Implement CanDeactivate guard on the component. Define a method (e.g., canDeactivate) that checks if form is dirty. The guard calls that method and asks for confirmation if needed.