Angular Interview Questions

34 Questions
Angular

Angular

FrontendWeb Development

Question 16

What is an Angular guard, and how do you implement one?

Answer:

An Angular guard is a feature used to control navigation in an Angular application. Guards determine whether a user can or cannot access a particular route. They are useful for implementing authentication, authorization, and other checks before navigating to a route. Angular provides several types of guards, including CanActivate, CanActivateChild, CanDeactivate, Resolve, and CanLoad.

Types of Angular Guards:

  1. CanActivate:

    • Determines if a route can be activated.
    • Typically used for authentication and authorization checks.
  2. CanActivateChild:

    • Determines if a child route can be activated.
    • Useful for protecting child routes of a route.
  3. CanDeactivate:

    • Determines if a route can be deactivated.
    • Often used to prevent users from leaving a component with unsaved changes.
  4. Resolve:

    • Resolves data before the route is activated.
    • Ensures that necessary data is loaded before navigating to a route.
  5. CanLoad:

    • Determines if a module can be loaded.
    • Useful for lazy loading modules based on certain conditions.

Implementing an Angular Guard:

Here’s a step-by-step guide to implementing a CanActivate guard to protect a route:

  1. Generate the Guard:

    • Use the Angular CLI to generate a guard.
      ng generate guard auth
  2. Implement the Guard Logic:

    • Implement the logic to check if the route can be activated. This typically involves checking some condition, such as whether the user is authenticated.
    • Example:
      import { Injectable } from '@angular/core';
      import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
      import { Observable } from 'rxjs';
      import { AuthService } from './auth.service';
      
      @Injectable({
        providedIn: 'root'
      })
      export class AuthGuard implements CanActivate {
      
        constructor(private authService: AuthService, private router: Router) {}
      
        canActivate(
          next: ActivatedRouteSnapshot,
          state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
          const isAuthenticated = this.authService.isAuthenticated();
          if (isAuthenticated) {
            return true;
          } else {
            this.router.navigate(['/login']);
            return false;
          }
        }
      }
  3. Register the Guard in Routes:

    • Apply the guard to routes in your routing module.
    • Example:
      import { NgModule } from '@angular/core';
      import { RouterModule, Routes } from '@angular/router';
      import { HomeComponent } from './home/home.component';
      import { AdminComponent } from './admin/admin.component';
      import { AuthGuard } from './auth/auth.guard';
      
      const routes: Routes = [
        { path: '', component: HomeComponent },
        { path: 'admin', component: AdminComponent, canActivate: [AuthGuard] }
      ];
      
      @NgModule({
        imports: [RouterModule.forRoot(routes)],
        exports: [RouterModule]
      })
      export class AppRoutingModule { }
  4. Implement the AuthService:

    • Create a service to handle authentication logic.
    • Example:
      import { Injectable } from '@angular/core';
      
      @Injectable({
        providedIn: 'root'
      })
      export class AuthService {
        private loggedIn = false;
      
        constructor() {}
      
        isAuthenticated(): boolean {
          // Replace with real authentication check logic
          return this.loggedIn;
        }
      
        login() {
          this.loggedIn = true;
        }
      
        logout() {
          this.loggedIn = false;
        }
      }

Example Scenario:

  1. Generating the Guard:

    ng generate guard auth
  2. Implementing the AuthGuard:

    import { Injectable } from '@angular/core';
    import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
    import { AuthService } from './auth.service';
    
    @Injectable({
      providedIn: 'root'
    })
    export class AuthGuard implements CanActivate {
    
      constructor(private authService: AuthService, private router: Router) {}
    
      canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): boolean {
        if (this.authService.isAuthenticated()) {
          return true;
        } else {
          this.router.navigate(['/login']);
          return false;
        }
      }
    }
  3. Registering the Guard in Routes:

    import { NgModule } from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';
    import { HomeComponent } from './home/home.component';
    import { AdminComponent } from './admin/admin.component';
    import { AuthGuard } from './auth.guard';
    
    const routes: Routes = [
      { path: '', component: HomeComponent },
      { path: 'admin', component: AdminComponent, canActivate: [AuthGuard] }
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }
  4. Implementing AuthService:

    import { Injectable } from '@angular/core';
    
    @Injectable({
      providedIn: 'root'
    })
    export class AuthService {
      private loggedIn = false;
    
      isAuthenticated(): boolean {
        return this.loggedIn;
      }
    
      login() {
        this.loggedIn = true;
      }
    
      logout() {
        this.loggedIn = false;
      }
    }

In Summary:

An Angular guard is a feature that controls access to routes based on specific conditions. To implement a guard, you create a guard class, define the logic to determine access, and register the guard with your routes. This ensures that only authorized users can navigate to protected parts of your application, enhancing security and user experience. Guards are versatile and can be used for various checks, such as authentication, authorization, and data preloading.

Recent job openings