Thuta Learning
IntermediateWeb Developmentintermediate

Custom Directives

Relax. We'll talk through this in plain words — no textbook voice.

Custom Directives let you create your own logic to modify the behavior of DOM elements.

typescript
// highlight.directive.ts
import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  @Input() highlightColor = 'yellow';
  
  constructor(private el: ElementRef) { }
  
  @HostListener('mouseenter') onMouseEnter() {
    this.highlight(this.highlightColor);
  }
  
  @HostListener('mouseleave') onMouseLeave() {
    this.highlight('');
  }
  
  private highlight(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
  }
}

// Usage in template
<p appHighlight highlightColor="lightblue">
  Hover over me!
</p>
You should see
(When you hover the mouse over the paragraph, a lightblue background appears)