Back to all posts

HostBinding and HostListener in Angular


What is @HostBinding?

The @HostBinding decorator is used to bind a property of the host element to a property in the directive or component class. This means that any changes made to the bound property in the class will automatically reflect on the host element. This is particularly useful for dynamically changing styles or attributes based on component logic.

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

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  @HostBinding('style.backgroundColor') backgroundColor: string;

  constructor() {
    this.backgroundColor = 'yellow'; // Sets the background color of the host element
  }
}

In this example, the appHighlight directive binds the backgroundColor property to the style.backgroundColor of the host element. When the directive is applied, it will change the background color of that element to yellow.

What is @HostListener?

The @HostListener decorator allows you to listen for events on the host element. When an event occurs, a specified method in your directive or component is invoked. This is useful for handling user interactions such as clicks, mouse movements, or keyboard events.

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

@Directive({
  selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
  @HostListener('click', ['$event'])
  onClick(event: MouseEvent) {
    console.log('Element clicked:', event);
  }
}

In this example, the appClickTracker directive listens for click events on its host element. When clicked, it logs a message to the console.

Use Cases

  1. Dynamic Styling with @HostBinding:
    • You can use @HostBinding to dynamically apply styles based on component state. For instance, changing colors or borders when certain conditions are met.
  2. Event Handling with @HostListener:
    • Use @HostListener to respond to user actions like clicks or mouse movements. This allows you to create interactive components without needing additional event binding in templates.