How to use CanActivate guard in Angular
CanActivate guards provide route-level protection in Angular applications by controlling access based on authentication, authorization, or custom business logic. As the creator of CoreUI with extensive Angular experience since 2014, I’ve implemented CanActivate guards in countless enterprise applications for security and access control. The most robust approach implements the CanActivate interface with conditional logic that returns boolean, Observable, or Promise values. This pattern enables fine-grained route protection while maintaining clean separation between routing and business logic.
Implement the CanActivate interface in a guard service and apply it to routes in your routing configuration.
import { Injectable } from '@angular/core'
import { CanActivate, Router, ActivatedRouteSnapshot } from '@angular/router'
import { Observable } from 'rxjs'
import { AuthService } from './auth.service'
@Injectable({
providedIn: 'root'
})
export class AdminGuard implements CanActivate {
constructor(
private authService: AuthService,
private router: Router
) {}
canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
return this.authService.hasRole('admin').pipe(
map(hasAdminRole => {
if (hasAdminRole) {
return true
} else {
this.router.navigate(['/unauthorized'])
return false
}
})
)
}
}
// In routing configuration
{
path: 'admin',
component: AdminComponent,
canActivate: [AdminGuard]
}
This code creates a CanActivate guard that checks if the user has admin role before allowing route access. The guard returns an ObservablecanActivate property in the route configuration.
Best Practice Note:
This is the authorization pattern we use in CoreUI Pro admin templates for role-based access control.
CanActivate guards can return boolean, Observable



