The
canActivateChild route guard in Angular allows you to check if a user is allowed to activate child routes. It is used to protect child routes of a particular route from being activated if certain conditions are not met.
When a user navigates to a child route, Angular checks if there is an associated canActivateChild guard in the parent route's route configuration. If there is, Angular executes the guard before activating the child route.
The canActivateChild guard is implemented as a service that implements the CanActivateChild interface. This interface has a single method, canActivateChild(), which returns a boolean or a promise that resolves to a boolean. If the method returns true, the child route is activated. If it returns false or a promise that resolves to false, the child route is not activated, and the user is redirected to a different route, or a custom error page is displayed.
Here is an example of how to use the canActivateChild route guard:
import { Injectable } from '@angular/core';
import { CanActivateChild, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivateChild {
canActivateChild(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable | Promise | boolean {
// Check if the user is authenticated
if (this.authService.isAuthenticated()) {
return true;
} else {
// If the user is not authenticated, redirect to the login page
this.router.navigate(['/login']);
return false;
}
}
}
In this example, we have an AuthGuard service that implements the CanActivateChild interface. The canActivateChild() method checks if the user is authenticated using a method isAuthenticated() provided by an AuthService. If the user is authenticated, the method returns true, allowing the child route to be activated. If the user is not authenticated, the method navigates to the login page and returns false, preventing the child route from being activated.
To use the AuthGuard service, you can add it to the canActivateChild property in the route configuration for the parent route that guards its child routes:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from './auth.guard';
import { ParentComponent } from './parent.component';
import { ChildComponent } from './child.component';
const routes: Routes = [
{
path: 'parent',
component: ParentComponent,
canActivateChild: [AuthGuard],
children: [
{
path: 'child',
component: ChildComponent
}
]
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
In this example, the canActivateChild property is set to an array containing the AuthGuard service. This guards the child route with the AuthGuard.
Still confused? if yes, check link
canActivateChild - tektutorialshub for explanation