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?
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
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With