Angular 20

Angular 20 Directives Tutorial – @if, @for, and Custom Directives Explained

Learning Directives in Angular 20 with @if else @for and @switch

Starting from Angular 17, a new block-based syntax using @if, @for, and @switch was introduced as an experimental feature to make templates more readable and maintainable. By Angular 20, this syntax is now fully stable and production-ready. These control-flow blocks provide a cleaner alternative to the traditional *ngIf and *ngFor structural directives. In this chapter, you’ll learn how to use these modern directives to create dynamic templates, handle conditional rendering, loop through data collections, and apply conditional logic — all directly within your HTML.

What Are Directives?

Directives are special features in Angular that let you attach behavior to DOM elements. They come in three main forms:
  • Component Directives – With templates
  • Structural Directives – Modify DOM layout (e.g., @if, @for)
  • Attribute Directives – Change appearance/behavior (e.g., [ngClass])
marks.component.html
<h2>Student Marks Summary</h2>

<p>Total Marks: {{ total }}</p>
<p>Average Marks: {{ average }}</p>

<!-- Modern @if/@else if/@else syntax -->
@if (average >= 90) {
  <p>🎉 Excellent performance!</p>
} @else if (average >= 75) {
  <p>👍 Good performance!</p>
} @else {
  <p>📚 Needs improvement!</p>
}

@for Loop

Use @for to iterate over collections:

<ul>
  @for (user of users; let i = $index) {
    <li>{{ i + 1 }}. {{ user.name }}</li>
  }
</ul>

Built-in Attribute Directive: [ngClass]

Use [ngClass] to dynamically apply CSS classes:

<h2>Student Marks Summary</h2>

<p>Total Marks: {{ total }}</p>
<p>Average Marks: {{ average }}</p>

<!-- Conditional class based on result -->
<div [ngClass]="{ 'pass': average >= 40, 'fail': average < 40 }">
  Result Status: {{ average >= 40 ? 'Pass' : 'Fail' }}
</div>

Creating a Custom Attribute Directive

Step 1: Generate

ng generate directive highlight

Step 2: Logic


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

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

  @HostListener('mouseenter') onMouseEnter() {
    this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor');
  }
}

Step 3: Usage


<p appHighlight>Hover to highlight me!</p>

Custom Structural Directive Example


<!-- ✅ marks.component.ts -->
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HighlightDirective } from './highlight.directive';

@Component({
  selector: 'app-marks',
  standalone: true,
  imports: [CommonModule, HighlightDirective],
  templateUrl: './marks.component.html',
  styleUrl: './marks.component.css'
})
export class MarksComponent {
  mathematics = 85;
  science = 78;
  english = 92;
  hindi = 88;
  history = 74;
  computerScience = 95;
}

<!-- ✅ marks.component.html -->
<h2>Student Marks Table</h2>
<table border="1">
  <tr>
    <th>Subject</th>
    <th>Marks</th>
  </tr>
  @for (subject of [
    { name: 'Mathematics', value: mathematics },
    { name: 'Science', value: science },
    { name: 'English', value: english },
    { name: 'Hindi', value: hindi },
    { name: 'History', value: history },
    { name: 'Computer Science', value: computerScience }
  ]) {
    <tr appHighlight>
      <td>{{ subject.name }}</td>
      <td>{{ subject.value }}</td>
    </tr>
  }
</table>

🔸 Using @switch for Grade Evaluation  Example

<h2>Grade Evaluation</h2>

<p>Marks: {{ marks }}</p>

@switch (true) {
  @case (marks >= 90) {
    <p>Grade: A+ 🌟</p>
  }
  @case (marks >= 80) {
    <p>Grade: A 👍</p>
  }
  @case (marks >= 70) {
    <p>Grade: B 🙂</p>
  }
  @case (marks >= 60) {
    <p>Grade: C 😐</p>
  }
  @case (marks >= 50) {
    <p>Grade: D 🙁</p>
  }
  @default {
    <p>Grade: F ❌</p>
  }
}

📌 In Component (marks.component.ts)

export class MarksComponent {
  marks = 76; // You can change this value to test output
}

Conclusion

Directives power the building blocks of modern Angular apps. With Angular 20’s clean syntax and standalone support, your UIs become more dynamic and maintainable.

Leave a Reply

Your email address will not be published. Required fields are marked *