title: Detect Browser or tab close - Angular
body: <p>I have a Angular 8 web application where an API is called whenever the browser is closed or the browser tab is closed where my application is running. I have tried the following code</p>
  
  <pre><code>    @Component({
       selector: 'app-root',
       templateUrl: './app.component.html',
       styleUrls: ['./app.component.scss']
      })
      export class AppComponent {
       @HostListener('window:beforeunload', ["$event"]) unload(event) {
          //calling api
       }
      }
  </code></pre>
  
  <p>The logic for the api (data in variables and functions) runs as expected, but only when i resize the browser window (inspect element) or add any breakpoint.
  I also tried <a href="https://v8.angular.io/api/core/Directive#host" rel="nofollow noreferrer">https://v8.angular.io/api/core/Directive#host</a> property.<br>
  Am i adding the listener to the wrong component or the DOM object or listener is getting removed or not getting added.</p>