Skip to content
the poor coder

angular cli generate guard

Poor Man
Published
Reading time
1 min read
On this page

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:
Bash
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
Bash
ng generate guard guard-name --implements CanActivate
  • CanActivateChild
Bash
ng generate guard guard-name --implements CanActivateChild
  • CanDeactivate
Bash
ng generate guard guard-name --implements CanDeactivate
  • Resolve
Bash
ng generate guard guard-name --implements Resolve
  • CanLoad
Bash
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.

TypeScript
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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC