HostListener and HostBinding Angular

Sweta PraharajSweta Praharaj
3 min read

HostListener and HostBinding in Angular

In Angular, @HostListener and @HostBinding are decorators that help interact with the host element (the element on which the directive or component is applied).


1. @HostListener - Listening to Events on the Host Element

The @HostListener decorator allows a directive/component to listen to DOM events on its host element.

Example: Change Background on Click

Let's create a directive that changes the background color when the user clicks on an element.

Step 1: Create a Directive

typescriptCopyEditimport { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {

  constructor(private el: ElementRef) {}

  @HostListener('click') onClick() {
    this.el.nativeElement.style.backgroundColor = 'yellow';
  }
}

Step 2: Use the Directive

Apply it to an element in a component template:

htmlCopyEdit<p appHighlight>Click me to change background!</p>

✅ Now, when you click on the <p> element, the background turns yellow.


2. @HostBinding - Binding Properties to the Host Element

The @HostBinding decorator allows you to bind properties of the host element to a class property.

Example: Toggle a Border on Mouse Hover

Let's modify our directive to add a border when hovering over an element.

Step 1: Modify the Directive

typescriptCopyEditimport { Directive, HostBinding, HostListener } from '@angular/core';

@Directive({
  selector: '[appBorder]'
})
export class BorderDirective {

  @HostBinding('style.border') border!: string;

  @HostListener('mouseenter') onMouseEnter() {
    this.border = '2px solid blue';
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.border = 'none';
  }
}

Step 2: Use the Directive

htmlCopyEdit<p appBorder>Hover over me to see a border!</p>

✅ When you hover over the element, it gets a blue border. When the mouse leaves, the border disappears.


Differences Between @HostListener and @HostBinding

Feature@HostListener@HostBinding
PurposeListens for events on the host elementBinds properties to the host element
Example UsageDetecting clicks, key presses, mouse eventsDynamically changing styles, attributes, classes

Real-World Use Case: Button Disable on Click

Let's build a directive that disables a button after the first click.

Directive Code

typescriptCopyEditimport { Directive, HostBinding, HostListener } from '@angular/core';

@Directive({
  selector: '[appDisableButton]'
})
export class DisableButtonDirective {

  @HostBinding('disabled') isDisabled = false;

  @HostListener('click') onClick() {
    this.isDisabled = true;
  }
}

Usage in Template

htmlCopyEdit<button appDisableButton>Click Me</button>

✅ Now, when you click the button once, it gets disabled.


Conclusion

  • Use @HostListener to listen for host element events.

  • Use @HostBinding to dynamically bind properties (like styles, attributes) to the host element.


Diagram: How @HostListener and @HostBinding Work

kotlinCopyEdit------------------------------------------------
|              Host Element                    |
|  <p appHighlight appBorder>                  |
|    Hover & Click on me!                      |
|  </p>                                        |
------------------------------------------------
        |                   |
        |                   |
        ▼                   ▼
   @HostListener          @HostBinding  
   - Listens to events    - Binds properties
   - (click, hover, etc.) - (style, class, attr, etc.)
        |                   |
        ▼                   ▼
------------------------------------------------
|          Angular Directive                   |
|                                              |
|  @Directive({ selector: '[appBorder]' })     |
|  class BorderDirective {                     |
|    @HostBinding('style.border') border;      |
|    @HostListener('mouseenter') onMouseEnter()| 
|    @HostListener('mouseleave') onMouseLeave()| 
|  }                                           |
------------------------------------------------

Explanation of the Flow

  1. User interacts with the element (clicks, hovers, etc.).

  2. The @HostListener decorator captures the event.

  3. Based on the event, the directive updates a property.

  4. The @HostBinding decorator binds the property to a CSS style, attribute, or class.

  5. The UI updates dynamically

0
Subscribe to my newsletter

Read articles from Sweta Praharaj directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sweta Praharaj
Sweta Praharaj