Welcome back to our Angular learning journey! Today we’re unlocking one of Angular’s most powerful features: Directives. These are tools that let you extend HTML with custom behavior and create reusable UI patterns.
What Are Directives?
Directives are classes that add additional behavior to DOM elements. Angular provides three types:
- Components (special directives with templates)
- Attribute Directives (change appearance/behavior)
- Structural Directives (alter DOM layout)
1. Built-in Structural Directives
These directives change the DOM structure by adding/removing elements.
ngIf – Conditional Display
html
<div *ngIf="isLoggedIn; else loggedOut"> Welcome back, user! </div> <ng-template #loggedOut> Please log in. </ng-template>
ngFor – List Rendering
typescript
items = ['Angular', 'React', 'Vue'];
html
<ul> <li *ngFor="let item of items; index as i"> {{ i + 1 }}. {{ item }} </li> </ul>
Additional template variables:
index
(current iteration)first
/last
(boolean)even
/odd
(boolean)
ngSwitch – Multiple Conditions
typescript
alertType = 'warning';
html
<div [ngSwitch]="alertType"> <div *ngSwitchCase="'success'">✅ Success!</div> <div *ngSwitchCase="'warning'">⚠ Warning!</div> <div *ngSwitchCase="'error'">❌ Error!</div> <div *ngSwitchDefault>ℹ Info</div> </div>
2. Built-in Attribute Directives
These change an element’s appearance or behavior.
ngClass – Dynamic CSS Classes
typescript
isActive = true; isDisabled = false;
html
<button [ngClass]="{ 'active': isActive, 'disabled': isDisabled, 'btn-large': true }"> Submit </button>
Alternative syntax:
html
<button [class.active]="isActive">Submit</button>
ngStyle – Dynamic Styles
typescript
progress = 65;
html
<div [ngStyle]="{ 'width.px': 200, 'height.px': 30, 'background-color': progress > 50 ? 'green' : 'red' }"> {{ progress }}% </div>
3. Creating Custom Directives
Let’s build a appHighlight
directive that changes background color on hover.
Step 1: Generate Directive
bash
ng generate directive highlight # Shorthand: ng g d highlight
Step 2: Implement Directive Logic
typescript
import { Directive, ElementRef, HostListener, Input } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { @Input() appHighlight = 'yellow'; @Input() defaultColor = 'transparent'; constructor(private el: ElementRef) {} @HostListener('mouseenter') onMouseEnter() { this.highlight(this.appHighlight); } @HostListener('mouseleave') onMouseLeave() { this.highlight(this.defaultColor); } private highlight(color: string) { this.el.nativeElement.style.backgroundColor = color; } }
Step 3: Use the Directive
html
<p [appHighlight]="'lightblue'" [defaultColor]="'white'"> Hover over me! </p>
Advanced Directive Techniques
Handling Input Changes
typescript
@Input() set appHighlight(color: string) { this._defaultColor = color || 'yellow'; } private _defaultColor: string;
Using Renderer2 (Safer DOM Manipulation)
typescript
constructor(private el: ElementRef, private renderer: Renderer2) {} private highlight(color: string) { this.renderer.setStyle( this.el.nativeElement, 'background-color', color ); }
Real-World Directive Examples
- Permission Directive (show/hide based on user roles)
- Auto-focus Directive (focus input on page load)
- Tooltip Directive (custom tooltip behavior)
- Click Outside Directive (close dropdowns when clicking outside)
Performance Considerations
- Avoid heavy operations in directives
- Use
OnPush
change detection where possible - Consider debouncing events like scroll/resize
Hands-On Exercise
Create a appPasswordStrength
directive that:
- Analyzes password input in real-time
- Shows visual feedback (weak/medium/strong)
- Uses color coding (red/yellow/green)
- Exposes strength percentage as an output
What’s Next?
In Part 6, we’ll explore Pipes – Angular’s powerful data transformation tools!