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:
ngClassngStyle- 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>
- βοΈ
*ngIfadds 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
*ngIffallback
π 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:
- When an input is rendered, it automatically gets focus.
- Should work like:
<input type="text" appAutoFocus />
Hints:
- Use
ElementRef - Use
ngAfterViewInit()