Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 12: Directives in Angular

Directives are Angular’s way of extending HTML with custom behavior. While components control entire views, directives attach behavior to existing DOM elements or templates.

There are three main kinds of directives in Angular:

  1. Component Directives – technically directives with templates.
  2. Structural Directives – change the DOM structure (e.g., *ngIf, *ngFor).
  3. Attribute Directives – change the appearance or behavior of elements (e.g., ngClass, custom highlight directive).

12.1 Built-in Attribute Directives

ngClass

Dynamically apply CSS classes:

<div [ngClass]="{ active: isActive, disabled: isDisabled }">Hello</div>

ngStyle

Apply inline styles dynamically:

<div [ngStyle]="{ color: isActive ? 'green' : 'red' }">Status</div>

12.2 Structural Directives

Structural directives shape or reshape the DOM. They use * prefix (syntactic sugar).

*ngIf

<p *ngIf="isLoggedIn">Welcome back!</p>

*ngFor

<li *ngFor="let item of items; index as i">
  {{ i }} – {{ item }}
</li>

12.3 Creating a Custom Attribute Directive

Let’s create a highlight directive.

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

@Directive({
  selector: '[appHighlight]',
  standalone: true
})
export class HighlightDirective {
  constructor(private el: ElementRef) {}

  @HostListener('mouseenter') onMouseEnter() {
    this.el.nativeElement.style.backgroundColor = 'yellow';
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.el.nativeElement.style.backgroundColor = '';
  }
}

Usage:

<p appHighlight>Hover over me!</p>

12.4 The New Angular Block Syntax (@for, @if)

Starting with Angular v17, we can use new block directives with @ syntax, replacing *ngFor and *ngIf.

Example: @if

@if (isLoggedIn) {
  <p>Welcome back!</p>
} @else {
  <p>Please log in</p>
}

✅ Clearer than *ngIf with else templates.


Example: @for

<ul>
  @for (item of items; track item.id; let i = $index) {
    <li>{{ i }} – {{ item.name }}</li>
  }
</ul>

✅ Differences from *ngFor:

  • No * prefix — uses block { ... } syntax.
  • Built-in tracking with track.
  • Cleaner handling of loop variables ($index, $first, $last, $odd, $even).
  • Easier to read in nested structures.

12.5 Comparison: *ngFor vs @for

Feature*ngFor@for (Angular v17+)
Syntax*ngFor="let item of items"@for (item of items) { ... }
Loop variablesindex as i, first, last, etc.$index, $first, $last, $odd, $even
TrackingtrackBy: fntrack item.id (inline)
ReadabilityNested <ng-template> for else casesBlock structure, cleaner
PerformanceGoodBetter, with compiler optimizations
RecommendationLegacy support, still worksPrefer @for for new projects

12.6 Migration Notes

  • *ngFor and *ngIf still work; plan for removal in version 22
  • New block directives are faster and more readable.
  • @for and @if is the recommended style.

12.7 Summary

  • Directives extend HTML behavior in Angular.
  • Attribute directives (e.g., ngClass) modify styles or behavior.
  • Structural directives (*ngIf, *ngFor) change DOM structure.
  • You can write your own custom directives for reusable logic.
  • Angular v17 introduces block syntax (@if, @for) — a modern, cleaner, and more optimized alternative.