angular cli generate guard

Angular CLI Generate Guard

If you want to protect your routes, you can use Angular Guards. Angular Guards are classes that implement the CanActivate interface, which decides whether a route can be activated or not. You can generate a Guard using the Angular CLI.

Steps to generate a Guard using the Angular CLI

  1. Open your terminal or command prompt.
  2. Navigate to your project folder.
  3. Run the following command:
ng generate guard guard-name

This command will generate a new file named guard-name.guard.ts in the src/app/ directory.

Different ways to generate a Guard using the Angular CLI

You can also use the following commands to generate different types of Guards:

  • CanActivate
ng generate guard guard-name --implements CanActivate
  • CanActivateChild
ng generate guard guard-name --implements CanActivateChild
  • CanDeactivate
ng generate guard guard-name --implements CanDeactivate
  • Resolve
ng generate guard guard-name --implements Resolve
  • CanLoad
ng generate guard guard-name --implements CanLoad

These commands will generate different types of Guards with the corresponding implements interface implemented.

Once you've generated a Guard, you can use it to protect your routes by adding it to the canActivate or canActivateChild properties in your routes configuration.

const routes: Routes = [
  {
    path: 'protected',
    component: ProtectedComponent,
    canActivate: [AuthGuard]
  }
];

In this example, the AuthGuard is used to protect the /protected route.

That's it! Now you know how to generate a Guard using the Angular CLI and how to use it to protect your routes.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe