Hello guys how are you? Welcome back to my blog. Today we will do In Angular 17, we can show an alert message when the window is about to be closed using the HostListener
decorator to listen for the beforeunload
event. This event fires when a window, frame, or tab is about to unload its resources.
Angular 17 came and Bootstrap 5 also. If you are new then you must check below two links:
Here’s how you can implement this in your Angular component:
- Import the necessary modules:
First, you need to importHostListener
from@angular/core
. - Add the HostListener to listen for the
beforeunload
event:
Use theHostListener
to trigger a function when the user tries to close the window. This function can show a confirmation dialog asking if the user really wants to leave the page.
Here’s an example implementation:
import { Component, HostListener } from '@angular/core'; @Component({ selector: 'app-root', template: `<p>Welcome to the app!</p>` }) export class AppComponent { @HostListener('window:beforeunload', ['$event']) unloadNotification($event: any) { $event.returnValue = "You have unsaved changes! Are you sure you want to leave?"; } }
Explanation:
- @HostListener(‘window:beforeunload’, [‘$event’]): This decorator listens for the
beforeunload
event. This event is fired just before the window is unloaded. - unloadNotification($event: any): This method is triggered when the
beforeunload
event is fired. It receives the event object as a parameter. - $event.returnValue = “…”: Setting
returnValue
on the event to a string message will prompt the user with a confirmation dialog including that message. This message may or may not be displayed depending on the browser, as some modern browsers display a generic message for security reasons.
Important Note:
Modern browsers have limited the capability to customize the message displayed in the confirmation dialog due to security reasons. Typically, browsers will show a generic message regardless of what is set in $event.returnValue
. This behavior is intended to prevent phishing and other deceptive practices.
This approach should be tested across different browsers to ensure consistent behavior as per your application’s requirements.
Guys if you will have any kind of query, suggestion or requirement then feel free to comment below.
Thanks
Recent Comments