Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Angular 9, how do you implement an onblur handler for a page?

I want to set an onblur event handler in my Angular 9 app for when someone leaves the page. My page in question is mapped to a single component that has this ...

export class HotComponent implements OnInit {
  ...

  onBlur(): void {
    console.log("on blur called !!!");
  }

In the template, I set this ...

<div (blur)="onBlur()">
  <div>
    ...
  </div>
</div>

But when I navigate away from the browser window where this page is loaded and come back, I notice the onblur handler hasn't been called. What's the proper way to implement the onblur event handler for a page in Angular 9?

like image 394
satish Avatar asked Sep 03 '25 02:09

satish


2 Answers

Angular has something called HostListener, you need to use it!

 /**
   * Blur
   * @param eventName 'focusout' is the key
   * @param arguments of type '$event'
   */
  @HostListener('focusout', ['$event'])
  onFocusout(event) {
    // your logic goes here
    console.log('on blur called'); // This will get printed on blur
  }
like image 189
Srikar Phani Kumar M Avatar answered Sep 05 '25 14:09

Srikar Phani Kumar M


I suggest you look into the onbeforeunload event. The onblur event isn't really designed to support your usecase because it targets the state change of an element. What you're attempting to do is intercept a history change on the browser.

The onbeforeunload property of the WindowEventHandlers mixin is the EventHandler for processing beforeunload events. These events fire when a window is about to unload its resources. At this point, the document is still visible and the event is still cancelable.

As outlined by the other replies, you can add an event listener via Angular's @HostListener annotation:

@HostListener('window:beforeunload')
foo() {
  // Do something here
}
like image 33
El-Mo Avatar answered Sep 05 '25 16:09

El-Mo