Skip to main content

Command Palette

Search for a command to run...

Activity 13 Research Angular Pipes

Published
6 min readView as Markdown
Activity 13 Research Angular Pipes

Research the Definition of Angular Pipes:

Understand what Angular Pipes are and their purpose.

→ Pipes are simple functions that take an input value, process it, and return a transformed output value. They help keep your templates clean and readable by offloading data formatting logic from your business logic.

Learn how pipes are used to transform data in templates (e.g., formatting dates, numbers, strings).

Formatting Dates

<p>Today's date is: {{ todayDate | date }}</p>
<p>Today's date (short format): {{ todayDate | date: 'shortDate' }}</p>
<p>Today's date (medium format): {{ todayDate | date: 'mediumDate' }}</p>
<p>Today's date (long format): {{ todayDate | date: 'longDate' }}</p>
<p>Today's date (full format): {{ todayDate | date: 'fullDate' }}</p>
<p>Today's date (custom format): {{ todayDate | date: 'dd/MM/yyyy' }}</p>

The date pipe is used to format dates in different ways. It accepts a date object as its input and an optional format string as its argument.

Formatting Numbers

<p>Price: {{ price | number }}</p>
<p>Price (with two decimal places): {{ price | number: '1.2-2' }}</p>
<p>Price (with currency symbol): {{ price | currency: 'USD' }}</p>

The number pipe formats numbers with different options, such as adding commas for thousands separators, specifying the number of decimal places, and applying currency symbols.

Formatting Strings

<p>Original string: {{ originalString }}</p>
<p>Uppercase: {{ originalString | uppercase }}</p>
<p>Lowercase: {{ originalString | lowercase }}</p>
<p>Titlecase: {{ originalString | titlecase }}</p>

The uppercase, lowercase, and titlecase pipes are used to change the case of strings.

Types of Angular Pipes:

Research built-in pipes such as DatePipe, CurrencyPipe, DecimalPipe, UpperCasePipe, LowerCasePipe, SlicePipe, and more.

DatePipe - Formats date values according to locale rules.

  • Syntax: {{ dateValue | date: 'format' }}

UpperCasePipe - Transforms text to uppercase.

  • Syntax: {{ text | uppercase }}

LowerCasePipe

Transforms text to lowercase.

  • Syntax: {{ text | lowercase }}

CurrencyPipe - Formats a number as currency.

  • Syntax: {{ number | currency: 'currencyCode': 'symbolDisplay': 'digitsInfo': 'locale' }}

    DecimalPipe - Formats a number as a decimal.

  • Syntax: {{ number | number: 'digitsInfo' }}

DecimalPipe - Formats a number as a decimal.

  • Syntax: {{ number | number: 'digitsInfo' }}

SlicePipe - Slices a string or array and returns a new substring or subarray.

  • Syntax: {{ value | slice: start: end }}

JsonPipe - Converts a value into its JSON string representation.

  • Syntax: {{ value | json }}

TitleCasePipe - Capitalizes the first letter of each word in a string.

  • Syntax: {{ text | titlecase }}

    Explore how to create custom pipes when built-in pipes don't meet the requirements.

→ Steps to Create a Custom Pipe:

  1. Generate the Pipe: Use the Angular CLI to generate a new pipe:

    This will create two files

   ng generate pipe myCustomPipe
  • my-custom-pipe.pipe.ts: Contains the pipe's logic.

  • my-custom-pipe.pipe.spec.ts: For testing the pipe.

    1. Implement the PipeTransform Interface
   import { Pipe, PipeTransform } from '@angular/core';

   @Pipe({
     name: 'myCustomPipe'
   })
   export class MyCustomPipe implements PipeTransform {
     transform(value: any, ...args: any[]): any {
       // Your custom transformation logic here
       return value;
     }
   }

The @Pipe decorator defines the pipe's metadata, including its name (myCustomPipe).

The PipeTransform interface requires you to implement the transform method.

  1. Write Transformation Logic
   import { Pipe, PipeTransform } from '@angular/core';

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

The transform method takes the input value (value) and any optional arguments (args) and returns the transformed output.

  1. Register the Pipe
   import { NgModule } from '@angular/core';
   import { MyCustomPipe } from './my-custom-pipe.pipe';

   @NgModule({
     declarations: [
       MyCustomPipe
     ],
     // ... other imports and providers
   })
   export class AppModule { }

Import and declare the pipe in your module's declarations array

  1. Use the Pipe in Your Template
   <p>Original: {{ myString }}</p>
   <p>Uppercase First: {{ myString | uppercaseFirst }}</p>

Use the pipe's name with the pipe operator (|) in your template

Example:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'fileSize'
})
export class FileSizePipe implements PipeTransform {
  transform(sizeInBytes: number, unit: string = 'KB'): string {
    const units = ['B', 'KB', 'MB', 'GB', 'TB'];
    let i = 0;
    while (sizeInBytes >= 1024 && i < units.length - 1) {
      sizeInBytes /= 1024;
      i++;
    }
    return `${sizeInBytes.toFixed(2)} ${units[i]}`;
  }
}

Use Cases of Angular Pipes:

Identify practical use cases for using pipes in Angular applications (e.g., displaying formatted dates, converting text to uppercase).

Find examples where pipes are used for dynamic data transformation in a user-friendly format.

→ Displaying Formatted Dates:

  • Use Case: Formatting dates to make them more readable for users.

  • Example: Using the date pipe to format a date object.

  • HTML

Converting Text to Uppercase:

  • Use Case: Transforming text to uppercase for emphasis or consistency.

  • Example: Using the uppercase pipe to convert text.

  • HTML

Currency Formatting:

  • Use Case: Displaying numbers as currency values.

  • Example: Using the currency pipe to format a number as currency.

  • HTML

Percentage Conversion:

  • Use Case: Converting numbers to percentage format.

  • Example: Using the percent pipe to display a number as a percentage.

  • HTML

Dynamic Data Transformation:

  • Use Case: Transforming data dynamically based on user input or other variables.

  • Example: Using the json pipe to display an object in JSON format for debugging.

  • HTML

Search for Code Snippets:

Look for code snippets that demonstrate how to use built-in Angular pipes in templates.

Search for examples on creating custom pipes in Angular.

→ Built-in Pipes:

  • DatePipe
<p>Today's date is: {{ todayDate | date }}</p>  
<p>Today's date (short): {{ todayDate | date: 'shortDate' }}</p>
<p>Today's date (medium): {{ todayDate | date: 'mediumDate' }}</p>
<p>Today's date (long): {{ todayDate | date: 'longDate' }}</p>
<p>Today's date (custom): {{ todayDate | date: 'dd/MM/yyyy' }}</p>

CurrencyPipe

<p>Price: {{ price | currency }}</p> 
<p>Price (Euro): {{ price | currency: 'EUR' }}</p>
<p>Price (symbol before): {{ price | currency: 'USD': 'symbol' }}</p>
<p>Price (code before): {{ price | currency: 'USD': 'code' }}</p>

DecimalPipe

<p>Number: {{ numberValue | number }}</p>
<p>Number (2 decimals): {{ numberValue | number: '1.2-2' }}</p>
<p>Number (no decimals): {{ numberValue | number: '1.0-0' }}</p>

UpperCasePipe and LowerCasePipe

<p>Original: {{ text }}</p>
<p>Uppercase: {{ text | uppercase }}</p>
<p>Lowercase: {{ text | lowercase }}</p>

SlicePipe

<p>All items: {{ items }}</p>
<p>First 3 items: {{ items | slice: 0:3 }}</p>
<p>Last 2 items: {{ items | slice: -2 }}</p>

Custom Pipes:

  • Custom Pipe to Format File Sizes

  •   import { Pipe, PipeTransform } from '@angular/core';
    
      @Pipe({
        name: 'fileSize'
      })
      export class FileSizePipe implements PipeTransform {
        transform(sizeInBytes: number, unit: string = 'KB'): string {
          const units = ['B', 'KB', 'MB', 'GB', 'TB'];
          let i = 0;
          while (sizeInBytes >= 1024 && i < units.length - 1) {
            sizeInBytes /= 1024;
            i++;
          }
          return `${sizeInBytes.toFixed(2)} ${units[i]}`;
        }
      }
    

Custom Pipe to Highlight Keywords

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'highlight'
})
export class HighlightPipe implements PipeTransform {
  transform(text: string, keyword: string): string {
    if (!keyword) {
      return text;
    }
    const regex = new RegExp(keyword, 'gi');
    return text.replace(regex, `<span class="highlight">${keyword}</span>`);
  }
}

Using Custom Pipes in Templates

<p>File size: {{ fileSize | fileSize }}</p>
<p>Highlighted text: {{ text | highlight: 'search' }}</p>

Add References:

More from this blog

Untitled Publication

66 posts