← Back to Chapters

Custom Directives

? Custom Directives

? Quick Overview

Custom directives in Angular let you extend HTML by attaching reusable behaviors to DOM elements. They encapsulate logic that can modify the appearance or behavior of elements directly in your templates, making your UI more interactive and expressive without repeating code.

In this topic, you’ll learn how to create a simple highlight directive, apply it in a component template, and understand how it works behind the scenes.

? Key Concepts

  • Directive – A class annotated with @Directive that adds custom behavior to elements.
  • Selector – The attribute (e.g. [appHighlight]) you use in templates to apply the directive.
  • ElementRef – Gives access to the host DOM element.
  • Renderer2 – Safely updates the DOM in a platform-independent way.
  • @HostListener – Listens to events on the host element (like mouseenter and mouseleave).

? Syntax & Theory

A basic custom directive is defined as a TypeScript class with the @Directive decorator. The decorator configuration usually includes:

  • selector – How the directive is used in the template (attribute, class, etc.).

Inside the directive class, you typically inject:

  • ElementRef – To reference the host element.
  • Renderer2 – To safely apply styles or attributes.

You can then react to events on the host element using @HostListener to run logic like adding or removing styles.

? Code Example: Creating a Custom Highlight Directive

TypeScript · Directive Class

? View Code Example
// highlight.directive.ts - simple background highlight directive
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {}

  @HostListener('mouseenter') onMouseEnter() {
    this.renderer.setStyle(this.el.nativeElement, 'background-color', 'yellow');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.renderer.removeStyle(this.el.nativeElement, 'background-color');
  }
}

? Using the Custom Directive in a Template

HTML · Component Template

? View Code Example
<!-- app.component.html - applying the appHighlight directive -->
<p appHighlight>Hover over this text to see the highlight effect!</p>

? What Happens When You Run This?

  • The directive appHighlight is attached to the <p> element.
  • When the mouse enters the paragraph, onMouseEnter() runs and sets a yellow background.
  • When the mouse leaves, onMouseLeave() removes the background color.
  • Renderer2 ensures DOM updates are safe and work across different platforms (browser, server, etc.).

In short: the text gets highlighted in yellow while the mouse is hovering over it, and returns to normal when the cursor moves away.

✅ Tips & Best Practices

  • Always prefer Renderer2 over direct DOM access for better security and platform support.
  • Give your directives meaningful selectors (like appHighlight) that reflect their purpose.
  • Combine @HostListener with @HostBinding for more advanced, reactive behaviors.
  • Don’t forget to declare your directive in the Angular module’s declarations array.

? Try It Yourself

  • Create a directive that changes the text color to red when the element is clicked.
  • Build a directive that automatically adds a tooltip (using title attribute) to any element.
  • Make a directive that disables a button after it is clicked once.

For example, as a challenge, extend the highlight directive so that the highlight color can be passed as an input like [appHighlight]="'lightgreen'".