🎨 Directives

Control flow, structural directives, attribute directives, and custom directives

About This Feature

Angular 17 introduced a new built-in control flow syntax using @if, @for, and @switch — replacing *ngIf and *ngFor for most cases. Attribute directives like ngClass and ngStyle modify appearance and behavior without changing DOM structure. You can also write custom directives with @HostListener.

Code Example

// New control flow (@if, @for, @switch) — Angular 17+
@if (isVisible) {
  <p>I am visible!</p>
} @else {
  <p>I am hidden.</p>
}

@for (item of items; track item) {
  <li>{{ '{{' }} item {{ '}}' }}</li>
} @empty {
  <li>No items</li>
}

@switch (status) {
  @case ('active')   { <span class="badge-success">Active</span> }
  @case ('inactive') { <span class="badge-danger">Inactive</span> }
  @default           { <span>Unknown</span> }
}

// Attribute directives
<div [ngClass]="{ 'active': isActive, 'highlight': isHighlighted }"></div>
<div [ngStyle]="{ color: textColor, fontSize: size + 'px' }"></div>

// Custom attribute directive
@Directive({ selector: '[appHighlight]', standalone: true })
export class HighlightDirective {
  @Input() appHighlight = 'yellow';
  @HostListener('mouseenter') onEnter() {
    this.el.nativeElement.style.backgroundColor = this.appHighlight;
  }
  @HostListener('mouseleave') onLeave() {
    this.el.nativeElement.style.backgroundColor = '';
  }
}

Live Demo

@if / @else

I am visible! ✓

@for (with @empty)

5 items
Apple × Banana × Cherry × Date × Elderberry ×

@switch

🔴 RED — Stop

ngClass

Operation completed successfully!

ngStyle


Custom Highlight Directive (hover over items)

Hover for Yellow
Hover for Green
Hover for Blue
Hover for Pink