How To Prevent Browser / Window Close Event Using HostListener In Angular 6+

This post shows how to prevent the Browser / Window close event Using HostListener in Angular 6+.

First Import HostListener in your app.component.ts file like:
import { HostListener } from '@angular/core';
And, Use this code to prevent window close:
  @HostListener('window:beforeunload', ['$event'])
   onWindowClose(event: any): void {
    // Do something

     event.preventDefault();
     event.returnValue = false;

  }
Here is the complete code for your reference:
import { Component, AfterContentInit } from '@angular/core';
import { HostListener } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  {

  title = 'Angular 8 Demo';

  constructor(){}

  @HostListener('window:beforeunload', ['$event'])
   onWindowClose(event: any): void {
    // Do something

     event.preventDefault();
     event.returnValue = false;

  }
}

Reference

Comments