Friday, 18 April 2025

Angular 19 | Chapter 4 | Pipes and Directives

 

In Angular, pipes and directives are two powerful features used to enhance templates and the behavior of DOM elements. Here's a breakdown of each:

 

Pipes

Pipes are used to transform data in templates.
 

📌 What they do:

  • Take in data as input.
  • Transform it into a desired format.
  • Output the transformed data.
     

🔧 Common Use Cases:

  • Formatting dates, currency, or numbers.
  • Converting strings to uppercase/lowercase.
  • Creating custom transformations (e.g., filtering lists).
     

🧪 Example (built-in pipe):

<p>{{ birthday | date:'longDate' }}</p>

This will format the birthday variable using Angular’s built-in date pipe.
 

🛠️ Custom Pipe Example:

@Pipe({name: 'capitalize'})
export class CapitalizePipe implements PipeTransform {
  transform(value: string): string {
    return value.charAt(0).toUpperCase() + value.slice(1);
  }
}
 

Usage:

<p>{{ 'hello' | capitalize }}</p> <!-- Output: Hello -->

 

Directives

Directives are used to change the appearance, behavior, or layout of DOM elements.

📌 Types of Directives:

  1. Structural Directives – change the DOM layout (e.g., *ngIf, *ngFor)
  2. Attribute Directives – change the appearance or behavior of an element (e.g., ngClass, ngStyle, custom ones)
     

🧱 Structural Directive Example:
 

<div *ngIf="isLoggedIn">Welcome back!</div>
 

🎨 Attribute Directive Example:
 

<p [ngStyle]="{color: 'blue'}">This text is blue.</p>
 

🛠️ Custom Attribute Directive Example:
 

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(el: ElementRef) {
    el.nativeElement.style.backgroundColor = 'yellow';
  }
}

 

Usage:

<p appHighlight>This text has a yellow background.</p>

 

🧠 Summary

Feature

Purpose

Example

Pipe

Transforms data in templates

{{ 'hello' | capitalize }}

Directive

Changes DOM behavior/structure

<div *ngIf="show">

 

 

No comments:

Post a Comment