Angular › Directives

How would you create a custom attribute directive in Angular?

Intermediate

Answer

You create a class decorated with the Directive decorator, specifying a selector that matches the attribute you want to use in templates, then use dependency injection to get a reference to the host element and modify its behavior or appearance.
import { Directive, ElementRef, Renderer2 } from '@angular/core';

@Directive({ selector: '[appHighlight]', standalone: true })
export class HighlightDirective {
  constructor(el: ElementRef, renderer: Renderer2) {
    renderer.setStyle(el.nativeElement, 'backgroundColor', 'yellow');
  }
}

// Used as: <p appHighlight>This text has a yellow background</p>
Real-world example A team builds a custom highlight directive to visually mark important text throughout their app, reusing the exact same directive on any element that needs the same yellow background treatment.

Common follow-ups: Why is Renderer2 recommended over directly manipulating the DOM element yourself?;How would you make this directive's highlight color configurable through an input?