@HostListener in Angular
@HostListener allows you to listen to events occurring on that element. It acts as the "ears" of your directive, triggering functions when the user interacts with the host.
Here is a comprehensive list of the most probable events you will listen to using @HostListener.
1. Mouse Events
These are the most common triggers for attribute directives, used for hover effects, clicks, and drag-and-drop.
- Click & Double Click:
- Hover Effects:
- Right Click:
2. Keyboard Events
Useful when your directive is attached to an input or a focusable element like a button. You can even filter for specific keys.
- General Keys:
- Specific Key Filters (Angular Special Syntax):
3. Focus and Form Events
Crucial for directives that handle validation or UI feedback on input fields.
- Focus & Blur:
- Input Changes:
4. Window and Document Events
Sometimes you need to listen for events that happen outside the specific element, like scrolling the page or resizing the window.
- Scrolling & Resizing:
Summary Table: Common Listeners
| Event Name | Use Case |
'click' | Triggering an action like a ripple effect or opening a menu. |
'mouseenter' / 'mouseleave' | Toggling hover styles or showing tooltips. |
'keydown.enter' | Submitting a text field when the user hits Enter. |
'focus' / 'blur' | Highlighting an input field when the user clicks inside. |
'window:scroll' | Creating a "sticky" header or "back to top" button. |
'dragover' / 'drop' | Handling file uploads or drag-and-drop UI logic. |
Pro Tip: Using the $event object
If you need specific data from the event (like mouse coordinates or the specific key pressed), you must pass ['$event'] as the second argument.