by Sai gowtham

Angular CanDeactivate guard tutorial

Angular CanDeactivate guard tutorial

In this tutorial, we will learn about how to use the canDeactivate guard in an angular router.

CanDeactivate guard

CanDeactivate guard is used to notifying the users, if they accidentally closing of the page in the middle of a data filling for example form submission.

Let’s see an example.

First, we need a create a new file called can-deactivate.guard.ts inside your app folder and add the below code.

can-deactivate.guard.ts
import { CanDeactivate } from '@angular/router';import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';

export interface CanComponentDeactivate {
    canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;}

@Injectable({
    providedIn: 'root',
})

export class CanDeactivateGuard implements
    CanDeactivate<CanComponentDeactivate> {

    canDeactivate(component: CanComponentDeactivate) {        return component.canDeactivate && component.canDeactivate();    }}

In the above code, we first imported CanDeactivate from the ‘@angular/router’ package and we created a CanComponentDeactivate interface.

Inside class CanDeactivateGuard we added a canDeactivate method which receives a component as an argument which contains canDeactivate method.

Note: If we use CanDeactivateGuard for the particular route, the same route component receives as an argument to canDeactivate() method.

Using CanDeactivate guard

Inside your appRoutes array, you need to choose a route that needs CanDeactivate guard.

const appRoutes: Routes = [
  { path: 'contact',
   component: ContactComponent,
   canDeactivate: [CanDeactivateGuard]  },
];

Now, we have choosen ContactComponent should need CanDeactivateGuard so that we need a create canDeactivate() method inside our ContactComponent.

contact.component.html
<form (submit)="onSubmit()">
    <input placeholder="name" name="name" [(ngModel)]="user.name" />
    <input placeholder="email" name="email" [(ngModel)]="user.email" />
    <button type="submit">Submit</button>
</form>
contact.component.ts
import { Component } from '@angular/core';
import { Observable } from 'rxjs';import { CanComponentDeactivate } from '../can-deactivate.guard';
@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.css']
})

export class ContactComponent implements CanComponentDeactivate {
  user = {
    name: '',
    email: ''
  };

  saved = false;

  onSubmit() {
    console.log(this.user.name, this.user.email);
    this.saved = true;
  }
  canDeactivate(): Observable<boolean> | Promise<boolean> | boolean {    if ((this.user.name.length > 0 || this.user.email.length > 0)        && !this.saved) {      return confirm('Your changes are unsaved!! Do you like to exit');    }    return true;  }
}

If the canDeactivate() method returns true the user is allowed to leave from this route or the user is notified, Like in the above code we are checking if the user is filled his name or email then we are notifying him by using a confirm dialog.

deactivate-example

Have you seen in the above image, where i have entered name sai and click on Home then confirm dialog is showing with a message (‘Your changes are unsaved!! Do you like to exit’) if we click on ok we are allowed to leave from this route or if we click on cancel we stay in this route.

Code repository

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course