All topics
Directivesintermediate

Host Binding and Host Listener

Explain @HostBinding and @HostListener as decorator-based tools for binding to and listening on a directive's host element.

@HostBinding and @HostListener are the decorator-based way to interact with the element a directive or component is attached to, and they're especially central to attribute directives, which have no template of their own to put bindings in — the host element is the only DOM they can touch. Interviewers ask about these because they're used constantly in custom directive code, and because Angular now offers a metadata-object alternative (the host property) that's worth contrasting them with.

@HostListener is like a doorbell wired directly into your own front door, alerting you the instant someone rings it; @HostBinding is like a smart doorplate that automatically updates itself to show 'Do Not Disturb' whenever you flip an internal switch.

Key Concepts

1
@HostBinding('property') binds a class property's value to a DOM property, attribute, class, or style on the host element — whenever the decorated property changes and change detection runs, Angular pushes the new value onto the host element, similar to how a template binding like [class.active] works, just targeting the host instead of a child element.
@HostBinding('property')[class.active]
2
@HostListener('eventName', ['$event']) attaches an event listener to the host element (or, with a target prefix like document: or window:, to a global target), calling the decorated method whenever that event fires and passing along any arguments you declare, most commonly the $event object.
@HostListener('eventName', ['$event'])document:window:$event
3
The interview-relevant nuance is that both decorators compile down to the same underlying host binding instructions as the host metadata object in @Component/@Directive, so they're functionally equivalent — the choice between them is largely a style preference, though Angular's docs and style guide increasingly favor the host object for new code since it consolidates all host-related configuration in one visible place instead of scattering it across decorated class members.
host@Component@Directive