'Conditionally show Alert using onbeforeunload in Angular

I want to show alert popup conditionally when I am in Edit mode. I tried using HostListener but it appears even when we are not in edit mode so I want to disable onbeforeunload event conditionally. For now All I know is onbeforeunload will help me provide alert box but it will appear for all the cases. The Code I am using is :

@HostListener('window:beforeunload',['$event'])
  defaultConfirmation(event : any): void {
    console.log(this.initiateEdit)
    if(this.initiateEdit) return true;
    else return false;
  }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source