What are route guards?
Route guards are mechanisms that control access to routes in Angular.
They decide: whether a route can be opened, whether you can leave it, whether a module should be loaded, and so on.
Main types of guard
CanActivate- whether a route can be entered;CanDeactivate- whether you can leave the current component;CanActivateChild- whether child routes can be entered;CanLoad- whether a lazy module can be loaded;CanMatch- a newer, flexible guard for checking a route match.
How it works:
A guard is simply a class with a method that returns true, false, or Observable/Promise<boolean>.
If it returns false, Angular does not let the user onto the route.
Example:
ts
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
canActivate(): boolean {
return isUserLoggedIn(); // true or false
}
}ts
{ path: 'admin', component: AdminComponent, canActivate: [AuthGuard] }Summary: A guard is a filter placed before a route, to keep out what should not be shown.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.