#angular #directives #templates #structural

Day 3 β€” Mastering Directives in Angular (ngIf, ngFor, ngSwitch + Custom Directives)

πŸ“˜ Day 3 β€” Mastering Directives in Angular (ngIf, ngFor, ngSwitch + Custom Directives)

Hands-on Angular tutorial β€” Zero to Hero, Day 3

Welcome back, hero! Today you will learn:

  • βœ”οΈ What directives are
  • βœ”οΈ Structural directives: *ngIf, *ngFor, *ngSwitch
  • βœ”οΈ Attribute directives: ngClass, ngStyle
  • βœ”οΈ How to build your own custom directive
  • βœ”οΈ How to apply directives in real-world UI components

Today is SUPER practical β€” lots of coding ⚑


🟦 1. What Is a Directive?

A directive is an instruction for Angular to change the DOM.

Angular has 3 categories:

βœ”οΈ 1. Structural Directives

These change the layout of the DOM. They always start with *.

Examples:

  • *ngIf
  • *ngFor
  • *ngSwitch

βœ”οΈ 2. Attribute Directives

These modify appearance or behavior of an element.

Examples:

  • ngClass
  • ngStyle
  • custom attribute directives

βœ”οΈ 3. Component Directives

A component is technically a directive with a template.


🟩 2. Structural Directive #1 β€” *ngIf

Create a simple toggler.

In app.component.ts:

show = signal(true);

toggle() {
  this.show.update(v => !v);
}

In app.component.html:

<button (click)="toggle()">Toggle Card</button>

<div *ngIf="show()"> πŸŽ‰ This card is visible! </div>
  • βœ”οΈ *ngIf adds or removes DOM
  • βœ”οΈ Uses signals directly inside template

🟩 3. Structural Directive #2 β€” *ngFor

Generate a new component:

ng g component user-list --standalone

user-list.component.ts

import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-user-list',
  standalone: true,
  templateUrl: './user-list.component.html'
})
export class UserListComponent {
  users = signal([
    { name: 'Alice', role: 'Designer' },
    { name: 'Bob', role: 'Developer' },
    { name: 'Charlie', role: 'Product Manager' }
  ]);
}

user-list.component.html

<ul>
  <li *ngFor="let user of users()">
    {{ user.name }} β€” {{ user.role }}
  </li>
</ul>
  • βœ”οΈ Loop through arrays
  • βœ”οΈ Access signal values using users()

🟩 4. Structural Directive #3 β€” *ngSwitch

Imagine a user status indicator.

app.component.ts

status = signal('online');

setStatus(s: string) {
  this.status.set(s);
}

app.component.html

<button (click)="setStatus('online')">Online</button>
<button (click)="setStatus('away')">Away</button>
<button (click)="setStatus('offline')">Offline</button>

<div [ngSwitch]="status()">
  <p *ngSwitchCase="'online'">🟒 Online</p>
  <p *ngSwitchCase="'away'">🟑 Away</p>
  <p *ngSwitchCase="'offline'">πŸ”΄ Offline</p>
  <p *ngSwitchDefault>βšͺ Unknown</p>
</div>
  • βœ”οΈ Another fundamental Angular tool
  • βœ”οΈ Great for dashboards and state-driven UIs

🟨 5. Attribute Directive β€” ngClass

Let’s style the user status dynamically.

<p [ngClass]="{
  'online': status() === 'online',
  'away': status() === 'away',
  'offline': status() === 'offline'
}">
  Status: {{ status() }}
</p>

styles

.online { color: green; }
.away { color: orange; }
.offline { color: red; }
  • βœ”οΈ Applies classes dynamically

🟨 6. Attribute Directive β€” ngStyle

<p [ngStyle]="{ 'font-size': status() === 'online' ? '20px' : '16px' }">
  User status: {{ status() }}
</p>
  • βœ”οΈ Use inline dynamic CSS
  • βœ”οΈ Useful for responsive UI logic

πŸŸ₯ 7. Build Your First Custom Directive (Interactive Highlight)

This is where you level up πŸ’ͺ Let’s build a β€œhover highlight” directive.

Generate:

ng g directive hover-highlight --standalone

hover-highlight.directive.ts

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

@Directive({
  selector: '[hoverHighlight]',
  standalone: true
})
export class HoverHighlightDirective {

  @Input('hoverHighlight') highlightColor = 'yellow';

  private originalColor = '';

  constructor(private el: ElementRef) {
    this.originalColor = this.el.nativeElement.style.backgroundColor;
  }

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

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

Use it in your HTML:

<p hoverHighlight="lightblue">Hover me to see the magic ✨</p>

<p hoverHighlight="pink">Hover me too!</p>
  • βœ”οΈ Now you understand attribute directives
  • βœ”οΈ You wrote DOM behavior code
  • βœ”οΈ You used HostListener + ElementRef

This is real frontend engineering.


🟦 8. Real-World Example: Todo List With Directives

Create a small todo component:

ng g component todo-list --standalone

todo-list.component.ts

import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-todo-list',
  standalone: true,
  templateUrl: './todo-list.component.html'
})
export class TodoListComponent {
  todos = signal(['Learn Angular', 'Practice Components', 'Master Directives']);
}

todo-list.component.html

<ul>
  <li *ngFor="let todo of todos(); let i = index">
    {{ i + 1 }}. {{ todo }}
  </li>
</ul>

<p *ngIf="todos().length === 0">Nothing to do πŸŽ‰</p>
  • βœ”οΈ Using *ngFor
  • βœ”οΈ Using index
  • βœ”οΈ Using *ngIf fallback

πŸŽ‰ End of Day 3 β€” What You Learned

Today you mastered:

  • βœ”οΈ What directives are
  • βœ”οΈ Structural directives: *ngIf, *ngFor, *ngSwitch
  • βœ”οΈ Attribute directives: ngClass, ngStyle
  • βœ”οΈ How to build a custom directive using:
    • @Directive
    • @HostListener
    • @Input
  • βœ”οΈ Combined them into real UI components

This is core Angular knowledge. You’re now coding like a real Angular developer.


πŸ§ͺ Day 3 Challenge

Build a directive:

πŸ‘‰ appAutoFocus

Requirements:

  1. When an input is rendered, it automatically gets focus.
  2. Should work like:
    <input type="text" appAutoFocus />

Hints:

  • Use ElementRef
  • Use ngAfterViewInit()