Directives

📚 What are Directives?

Directives are classes that add additional behavior to elements in Angular applications.

  • Component Directives: Directives with templates (Components are directives!)
  • Attribute Directives: Change appearance or behavior of elements (ngClass, ngStyle)
  • Structural Directives: Change DOM structure (@if, @for, @switch in v17+)

🎯 Interview Questions

  • Q1: What is the difference between structural and attribute directives?
  • A: Structural directives modify DOM structure (add/remove elements), attribute directives modify element appearance/behavior.
  • Q2: How do you create a custom directive?
  • A: Use @Directive decorator with a selector. Inject ElementRef to access the element.
  • Q3: What is the host property in directives?
  • A: Allows binding to host element properties, attributes, and events without @HostBinding/@HostListener.

🔧 Live Demo - Attribute Directive

👆 Hover over me! I have a custom highlight directive (light blue)

👆 Hover over me too! Different color (light green)

👆 Default color (yellow)

📋 Built-in Directives

Attribute Directives:

  • NgClass (use [class] instead)
  • NgStyle (use [style] instead)
  • NgModel

Structural (v17+ syntax):

  • @if / @else
  • @for with track
  • @switch / @case
  • @defer

💻 Custom Directive Code


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

@Directive({
  selector: '[appHighlight]',
})
export class HighlightDirective {
  private readonly el = inject(ElementRef);
  
  // Signal input (Angular 18+)
  appHighlight = input<string>('yellow');

  @HostListener('mouseenter') onMouseEnter() {
    this.highlight(this.appHighlight() || 'yellow');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.highlight('');
  }

  private highlight(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
  }
}

// Usage in template:
// <p appHighlight="lightblue">Hover me!</p>