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.
@Directive that adds custom behavior to elements.[appHighlight]) you use in templates to apply the directive.mouseenter and mouseleave).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.
TypeScript · Directive Class
// 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');
}
}
HTML · Component Template
<!-- app.component.html - applying the appHighlight directive -->
<p appHighlight>Hover over this text to see the highlight effect!</p>
appHighlight is attached to the <p> element.onMouseEnter() runs and sets a yellow background.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.
Renderer2 over direct DOM access for better security and platform support.appHighlight) that reflect their purpose.@HostListener with @HostBinding for more advanced, reactive behaviors.declarations array.title attribute) to any element.For example, as a challenge, extend the highlight directive so that the highlight color can be passed as an input like [appHighlight]="'lightgreen'".