How To Implement CanDeactivateFn in Angular15?
Last Updated :
12 Jul, 2024
The CanDeactivateFn
is a function in Angular that allows you to control whether a route can be deactivated or not. It's often used to prevent users from navigating away from a page with unsaved changes. In this article, we will see how to implement CanDeactivateFn in Angular15.
Approach
- Using a function: canDeactivate: () => boolean
- Using a class: canDeactivate: CanDeactivateFn
Steps to Create an Application
Step 1: Install Node.js and npm (if you haven't already).
npm install -g @angular/cli
Step 2: Create a new Angular project
ng new can-deactivate-demo
cd can-deactivate-demo
Step 3: Generate the components
ng generate component contact-us
ng generate component welcome
ng generate component register-user
Step 4: Install the required modules
ng add @angular/router
Project Structure
Folder StructureDependencies
{
"dependencies": {
"@angular/animations": "^15.0.0",
"@angular/common": "^15.0.0",
"@angular/compiler": "^15.0.0",
"@angular/core": "^15.0.0",
"@angular/forms": "^15.0.0",
"@angular/platform-browser": "^15.0.0",
"@angular/platform-browser-dynamic": "^15.0.0",
"@angular/router": "^15.0.0",
"rxjs": "~7.5.0",
"tslib": "^2.3.0",
"zone.js": "~0.11.4"
}
}
Approach 1: Using a Function
You can implement CanDeactivateFn as a function that returns a boolean value indicating whether the route can be deactivated or not.
HTML
<!--contact-us.component.html-->
<h1>Contact Us</h1>
<button routerLink="/welcome">Welcome</button>
HTML
<!--welcome.component.html-->
<h1>Welcome</h1>
<button routerLink="/register-user"> Register User</button>
HTML
<!--register-user.component.html-->
<h1>Register User</h1>
<button routerLink="/contact-us > Contact Us</button>
JavaScript
//can-deactivate.guard.ts
import { CanDeactivateFn } from '@angular/router';
export const canDeactivateFn: CanDeactivateFn = (component: any) => {
return component.canDeactivate ? component.canDeactivate() : true;
};
JavaScript
//contact-us.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-contact-us',
templateUrl: './contact-us.component.html',
styleUrls: ['./contact-us.component.css']
})
export class ContactUsComponent {
hasUnsavedChanges = true;
canDeactivate(): boolean {
return confirm("Do you want to leave this page? Unsaved changes will be lost.");
}
}
JavaScript
//app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ContactUsComponent } from './contact-us/contact-us.component';
import { WelcomeComponent } from './welcome/welcome.component';
import { RegisterUserComponent } from './register-user/register-user.component';
import { canDeactivateFn } from './can-deactivate.guard';
const routes: Routes = [
{ path: 'contact-us', component: ContactUsComponent, canDeactivate: [canDeactivateFn] },
{ path: 'welcome', component: WelcomeComponent },
{ path: 'register-user', component: RegisterUserComponent },
{ path: '', redirectTo: '/contact-us', pathMatch: 'full' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Output
How to implement CanDeactivateFn in Angular15Approach 2: Using a Class
You can implement CanDeactivateFn as a class that implements the CanDeactivate interface.
HTML
<!--contact-us.component.html-->
<h1>Contact Us</h1>
<button routerLink="/welcome"> Welcome</button>
HTML
<!--welcome.component.html-->
<h1>Welcome</h1>
<button routerLink="/register-user" >Register User</button>
HTML
<!--register-user.component.html-->
<h1>Register User</h1>
<button routerLink="/contact-us"> Contact Us</button>
JavaScript
//app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ContactUsComponent } from './contact-us/contact-us.component';
import { WelcomeComponent } from './welcome/welcome.component';
import { RegisterUserComponent } from './register-user/register-user.component';
import { CanDeactivateGuard } from './can-deactivate.guard';
const routes: Routes = [
{ path: 'contact-us', component: ContactUsComponent, canDeactivate: [CanDeactivateGuard] },
{ path: 'welcome', component: WelcomeComponent },
{ path: 'register-user', component: RegisterUserComponent },
{ path: '', redirectTo: '/contact-us', pathMatch: 'full' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
JavaScript
//contact-us.component.ts
import { Component } from '@angular/core';
import { CanComponentDeactivate } from '../can-deactivate.guard';
@Component({
selector: 'app-contact-us',
templateUrl: './contact-us.component.html',
styleUrls: ['./contact-us.component.css']
})
export class ContactUsComponent implements CanComponentDeactivate {
canDeactivate(): boolean {
return confirm("Do you want to leave this page? Unsaved changes will be lost.");
}
}
JavaScript
//can-deactivate.guard.ts
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
export interface CanComponentDeactivate {
canDeactivate: () => boolean;
}
@Injectable({
providedIn: 'root',
})
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(component: CanComponentDeactivate): boolean {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
Output
How To Implement CanDeactivateFn in Angular15?
Similar Reads
How to Generate CanActivate In Angular?
In Angular, protecting routes is important to make sure that unauthorized users cannot access certain parts of your application. The CanActivate interface allows you to implement route guards that determine whether a route can be activated based on specific conditions, such as user authentication or
5 min read
How to create module with Routing in Angular 9 ?
Angular applications are modular, and NgModules is Angular's own modular architecture. NgModules are containers for closely integrated application domains, workflows, or feature sets that comprise cohesive code blocks. Their scope is governed by the NgModule they include, and they can contain compon
4 min read
Component Communication in Angular
Angular, as a robust front-end framework, allows you to build complex and interactive web applications by creating reusable components. One of the key aspects of building such applications is effective communication between these components. There are a lot of instances where we need to transfer dat
12 min read
How To Use @Injectable Decorator In Angular?
In Angular, the @Injectable decorator is used to mark a class as available for dependency injection. This allows Angular to create and manage instances of this class and inject it into other components, services, or other classes.In this article, we will see how to use the @Injectable decorator in a
3 min read
How to Use & Create custom directive in Angular?
Directives in Angular are nothing but the classes that allow us to add and modify the behavior of elements. Using directives in angular we can modify the DOM (Document Object Module) styles, handle user functionality, and much more. Table of Content Custom DirectivesSteps to create the DirectiveBene
3 min read
How to call a function on click event in Angular2 ?
A Function is a set of statements that takes input, does some specific computation, and produces output. An on click event occurs when the user clicks on an element. In this article, we will see How to call a function on click event in Angular2, along with understanding the basic implementation thro
3 min read
How to disable a form control in Angular ?
In this article, we are going to see how to disable a form control in Angular 10. We will use AbstractControl disabled property to disable a form control element. Syntax: <formelement disabled></formelement> Return Value: boolean: returns boolean stating whether the element is disabled o
2 min read
AngularJS ng-model-options Directive
The ng-model-options directive has the feature which helps the user to modify, within the current application, the behavior of the ngModel directives. Basically, it is in use when the user has to control the binding of a variable and an HTML form element in the scope. You can also specify the amount
2 min read
How to Use the Async Pipe in Angular?
The AsyncPipe in Angular is a powerful and convenient tool used to handle asynchronous data streams such as observables and promises directly in the component template. It automatically subscribes to observables, renders their values, and updates the view when new data is emitted. This removes the n
3 min read
Angular PrimeNG Form Calendar Date Restriction Component
Angular PrimeNG is a collection of Interactive UI components for Angular applications. Developers can use these components to make beautiful and responsive web interfaces in no time as most of the components have all the necessary functions implemented. In this article, we will be discussing the Ang
3 min read