Part 5: Directives in Angular – Extending HTML’s Power

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:

  1. Components (special directives with templates)
  2. Attribute Directives (change appearance/behavior)
  3. 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

  1. Permission Directive (show/hide based on user roles)
  2. Auto-focus Directive (focus input on page load)
  3. Tooltip Directive (custom tooltip behavior)
  4. 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:

  1. Analyzes password input in real-time
  2. Shows visual feedback (weak/medium/strong)
  3. Uses color coding (red/yellow/green)
  4. Exposes strength percentage as an output

What’s Next?

In Part 6, we’ll explore Pipes – Angular’s powerful data transformation tools!

Leave a Comment

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