Author -  Sai gowtham

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

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY