ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

Angular Guards Tutorial

Angular Route Guards help us prevent the user from accessing certain parts of the applications under specific conditions. We can also use it to perform some actions before navigating to a route or leaving the route. The use cases for route guards are authorization, authentication, data collection, etc. The Angular supports several guards like CanActivate, CanDeactivate, Resolve, CanLoad, CanActivateChild, etc. This article will explore Angular Guards in detail by building an example Angular Guards application.

Angular Route Guards

We use the Angular Guards to control whether users can navigate to or away from the current route.

We looked at how to configure our routes and navigate to the different parts of our application in our Angular Router Tutorial. Allowing the user to navigate all application parts is not a good idea. We must restrict the user until the user performs specific actions like logging in etc. Angular provides the Route Guards for this purpose.

One of the common scenarios where we use Route guards is authentication. We want our app to stop the unauthorized user from accessing the protected route. We achieve this by using the CanActivate guard, which angular invokes when the user tries to navigate into the protected route. Then we hook into the href="#" CanActivate guard and use the authentication service to check whether the user is authorized to use the route or not. If he is not authenticated, then we can redirect the user to the login page.

Uses of Angular Route Guards

  1. To Confirm the navigational operation
  2. Asking whether to save before moving away from a view
  3. Allow access to certain parts of the application to specific users.
  4. Validating the route parameters before navigating to the route
  5. Fetching some data before you display the component.

Types of Route Guards

The Angular Router supports six different guards, which you can use to protect the route.

  1. CanActivate
  2. CanDeactivate
  3. Resolve
  4. CanLoad
  5. CanActivateChild
  6. CanMatch

CanActivate

The Angular CanActivate guard decides if a route can be activated ( or the component gets rendered). We use this guard when we want to check on some condition, before activating the component or showing it to the user. This allows us to cancel the navigation.

Use cases

  • Checking if a user has logged in
  • Checking if a user has permission
  • One of the use cases of this guard is to check if the user has logged in to the system. If the user has not logged in, then the guard can redirect him to the login page.

    Read: Angular CanActivate Guard Example

    CanDeactivate

    This Angular Guard decides if the user can leave the component (navigate away from the current route). This route is useful when the user might have some pending changes, which is not yet saved. The CanDeactivate route allows us to ask for user confirmation before leaving the component. You might ask the user if it’s OK to discard pending changes rather than save them.

    Read: Angular CanDeactivate Guard Example

    Resolve

    This guard delays the activation of the route until some tasks are complete. You can use the guard to pre-fetch the data from the backend API before activating the route.

    CanLoad

    The CanLoad Guard prevents the loading of the Lazy Loaded Module. We generally use this guard when we do not want to unauthorized users to be able even to see the source code of the module.

    This guard works similarly to CanActivate guard with one difference. The CanActivate guard prevents a particular route from being accessed. The CanLoad prevents the entire lazy-loaded module from being downloaded, protecting all the routes within that module.

    Read: Angular CanLoad Guard Example

    CanActivateChild

    CanActivateChild guard determines whether a child route can be activated. This guard is very similar to CanActivateGuard. We apply this guard to the parent route. The Angular invokes this guard whenever the user tries to navigate to any of its child routes. This allows us to check some conditions and decide whether to proceed with the navigation or cancel it.

    Read: Angular CanActivateChild Guard Example

    How to Build Angular Route Guards

    Building the Guards is very easy.

    1. Build the Guard as Service.
    2. Implement the Guard Method in the Service
    3. Register the Guard Service in the Root Module
    4. Update the Routes to use the guards

    1. Build the Guard as a Service

    Building the Guard Service is as simple as building any other Angular Service. You need to import the corresponding guard from the Angular Router Library using the Import statement. For Example use CanActivate Guard import the CanActivate in the import the CanActivate in the import statement

                                  
    
    import { CanActivate } from '@angular/router';
                                
                            

    Next, create the Guard class, which implements the selected guard Interface as shown below.

                                  
    
    @Injectable()
    export class ProductGuardService implements CanActivate {}
                                
                            

    You can also inject other services into the Guards using the Dependency Injection

    2. Implement the Guard Method

    The next step is to create the Guard Method. The name of the Guard method is the same as the Guard it implements. For Example, to implement the CanActivate guard, create a method CanActivate

                                  
     
    canActivate(): boolean {    
        // Check weather the route can be activated;    
        return true;     
        // or false if you want to cancel the navigation; 
    }
     
                                
                            

    The return value from the Guard

    The guard method must return either a True or a False value.

    If it returns true, the navigation process continues. if it returns false, the navigation process stops, and the user stays put.

    The above method returns a True value. The Guard can also return an Observable or a Promise, which eventually returns a True or false. The Angular will keep the user waiting until the guard returns true or false.

    The guard can also tell the router to navigate elsewhere, effectively canceling the current navigation.

    3. Register the Guard as Service in Module

    As mentioned earlier, guards are nothing but services. We need to register them with the providers array of the Angular Module as shown below.

                                  
    
    providers: [ProductService,ProductGuardService]
                                
                            

    The Angular router requires the Guards and all other services the guard depends on to be available during the navigation. Hence, the guards must be provided at the module level. This allows the router to access the guards using the Dependency Injection.

    4. Update the Routes

    Finally, we need to add the guards to the routes array, as shown below

                                  
    
    { path: 'product', component: ProductComponent, canActivate : [ProductGuardService] 
    }
     
                                
                            

    The above code adds the canActivate guard (ProductGuardService) to the Product route.

    When the user navigates to the Product route, Angular calls the canActivate method from the ProductGuardService. If the method returns true, then the ProductComponent is rendered.

    You can add more than one guard, as shown below

                                  
     
    { path: 'product', 
      component: ProductComponent, 
      canActivate : [ProductGuardService, AnotherProductGuardService ] 
    }
     
                                
                            

    The syntax for adding other guards is also similar

                                  
     
    { path: 'product', component,        
        canActivate : any[],        
        canActivateChild: any[],       
        canDeactivate: any[],       
        canLoad: any[],       
        resolve: any[] 
    }
                                
                            

    Order of execution of route guards

    A route can have multiple guards, and you can have guards at every level of a routing hierarchy.

    CanDeactivate() and CanActivateChild() guards are always checked first. The checking starts from the deepest child route to the top.

    CanActivate() Guard is checked next, and checking starts from the top to the deepest child route.

    CanLoad() Is invoked next If the feature module is to be loaded asynchronously.

    Resolve() Guard is invoked last.

    Resolve() Guard is invoked last.

    The Angular Router cancels the navigation If any of the guards return false.

    Angular Guards Example

    Let us update the App, which we built in the previous tutorials on Angular Routers, and use the CanActivate Guard to prevent the user from activating the ProductComponent

    The source code for this tutorial is available on GitHub

    Guard Service

    We create Guard classes as a service. Create a file named product-guard.service.ts in the src/app folder and add the following code

                                  
     
    import { Injectable } from '@angular/core';
    import { Router, CanActivate, ActivatedRouteSnapshot,RouterStateSnapshot } from '@angular/router';
     
    @Injectable()
    export class ProductGuardService implements CanActivate {
     
      constructor(private _router:Router ) {      
      }      
     
      canActivate(route: ActivatedRouteSnapshot,
                  state: RouterStateSnapshot): boolean {
          console.log("canActivate");      //return true    
         //remove comments to return true              
         alert('You are not allowed to view this page. You are redirected to Home Page'); 
         this._router.navigate(["home"]);             
         return false;     
    } }
     
                                
                            

    First, we need to import the Router, CanActivate, ActivatedRouteSnapshot & RouterStateSnapshot libraries from the angular/core package

                                  
    import { Router, CanActivate, ActivatedRouteSnapshot,RouterStateSnapshot } from '@angular/router';
     
                                
                            

    Define the ProductGuardService, which implements the CanActivate Interface

                                  
    
    export class ProductGuardService implements CanActivate {
                                
                            

    Finally, define the canActivate method

    The canActivate method accepts two arguments. The first argument is an ActivatedRouteSnapshot object, which describes the route that is being navigated to using the properties. The second argument is a RouterStateSnapshot object, which describes the current route through a single property called URL.

                                  
     
    canActivate(route: ActivatedRouteSnapshot, 
               state: RouterStateSnapshot): boolean {    
     
        console.log("canActivate");     //return true 
        //remove comments to return true   
        alert('You are not allowed to view this page. You are redirected to Home Page');    
        //this._router.navigate(["home"]); //navigate to some other route;    
        return false;
    }
     
                                
                            

    Import the Guard in the Root Module

                                  
     
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { HttpModule } from '@angular/http';
    import { RouterModule } from '@angular/router';
    import { AppComponent } from './app.component';
    import { HomeComponent} from './home.component';
    import { ContactComponent} from './contact.component';
    import { ProductComponent} from './product.component';
    import { ErrorComponent} from './error.component';
    import { ProductDetailComponent} from './product-detail.component';
    import { ProductService } from './product.service';
    import { ProductGuardService } from './product-guard.service';
    import { appRoutes } from './app.routes';
     
    @NgModule({
      declarations: [ AppComponent,HomeComponent,ContactComponent, 
                     ProductComponent,ErrorComponent, 
                     ProductDetailComponent],     
      imports:      [ BrowserModule, FormsModule,HttpModule,                
                     RouterModule.forRoot(appRoutes)],     
      providers:    [ ProductService,ProductGuardService ], 
      bootstrap:    [ AppComponent]
    })
    export class AppModule { }
     
                                
                            

    First, Import the Guard Service as shown below

                                  
     
    import { ProductGuardService } from './product-guard.service';
                                
                            

    Next, Register it using the Providers metadata so that that router can use it. Remember that Guards must be provided at the angular module level

                                  
     
    providers: [ProductService,ProductGuardService],
                                
                            

    Update the Routes

    Finally, Update the app.routes class

                                  
    
    import { Routes } from '@angular/router'; 
    import { HomeComponent} from './home.component';
    import { ContactComponent} from './contact.component';
    import { ProductComponent} from './product.component';
    import { ErrorComponent} from './error.component';
    import { ProductDetailComponent} from './product-detail.component';
    import { ProductGuardService } from './product-guard.service';
     
    export const appRoutes: Routes = [     
      { path: 'home', component: HomeComponent },     
      { path: 'contact', component: ContactComponent },     
      { path: 'product', component: ProductComponent, canActivate :[ProductGuardService] },     
      { path: 'product/:id', component: ProductDetailComponent },     
      { path: '', redirectTo: 'home', pathMatch: 'full' },     
      { path: '**', component: ErrorComponent }
    ];
     
                                
                            

    The only change we have made is to attach the ProductGuardService to the CanActivate guard

                                  
     
    { path: 'product', 
      component: ProductComponent, 
      canActivate : [ProductGuardService] },
     
                                
                            

    Test the Guard. Run the app, and you will see the alert message “You are not allowed to view this page”. You are redirected to the Home Page.

    Summary

    The angular Guards are a great tool that helps us to protect the route. They also help us run some logic, get data from the back-end server, etc. You can also create multiple guards against a single route or use the same guard against multiple routes.