In this article, you will learn how to create an auth guard with angular 11. For some time protect the URL and use the Guard, so in this case read the launch of Authguard in Angular 11.

In this tutorial, we will learn that if a user only logs in he should not go to the dashboard or any other page, he should go to the login page as you would see on any other website. angular auth guard to set it up, which we will see below.

Implementing angular authorized monitoring 11 To complete this process we will use a canactivate angular auth guard. We can use the Angular Router using these simple steps:


Step 1 - Create an angular app

First of all, create a new angular app "ng new angularauthguard". Let's create an angular app using the following commands.

ng new angularauthguard

Step 2 - Create a Guard

Let's open your created app. Create Authguard with the following command: auth is a folder name.

ng g guard auth/login


To create an Angular guard, you need to select the CanActivate.




Step 3 - Create a login

In this step we will create simple login, we will change the login page to open the login.component.ts file which can now be seen below. we use localStorage.setItem this we want to store what we want to store in our localstorage, we can use it, we will log in


login.component.html


import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor() { }
  userid = '1';
  ngOnInit(): void {
    localStorage.setItem('session', this.userid)
  }

}


Step 4 - Write a login guard code

Open the login.guard.ts file and change the code to what is given below:


auth/login.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class LoginGuard implements CanActivate {
  constructor( private routes: Router){}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {
      if (localStorage.getItem('session') != null) {
        return true;
      }
      else {
        this.routes.navigate(['/login']);
        return false;
      }
  }
  
}

Step 5 - Create a route

Use canActivate property of the Route interface to guard the route, for example, AuthGuard. Now find the canActivate property used in route declarations.


app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { QRCodeModule } from 'angularx-qrcode';
import { LoginComponent } from './login/login.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { LoginGuard } from './auth/login.guard'; // -------- import this guard----

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    DashboardComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    QRCodeModule
  ],
  providers: [ LoginGuard],     //---------- Update this code and import
  bootstrap: [AppComponent]
})
export class AppModule { }


app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginGuard } from './auth/login.guard';
import { DashboardComponent } from './dashboard/dashboard.component';
import { LoginComponent } from './login/login.component';

const routes: Routes = [
  {path: 'login', component:LoginComponent},
  {path:'', component:DashboardComponent , canActivate:[LoginGuard]}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

I hope it can help you...