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 the 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 which routes 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 canDeactivate method return true the user is allowed to leave from this route else the user is notified Like in the above code we are checking for if the user is filled 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 else if we click on cancel we stay in this route.

Code repository