Skip to main content

Command Palette

Search for a command to run...

Angular Pipes

Published
3 min readView as Markdown

Angular Pipes

  • Based on Angular Documentation:

    • In Angular template expressions, pipes are a unique operator that lets you transform data declaratively within your template. With pipes, you may define a transformation function once and apply it to several templates at once. Inspired by the Unix pipe, angular pipes use the vertical bar character (|).

    • Brief code overview about pipes from Angular Documentation as well.

    import { Component } from '@angular/core';
    import { CurrencyPipe, DatePipe, TitleCasePipe } from '@angular/common';
    @Component({
      selector: 'app-root',
      standalone: true,
      /*
      Here we use Currency, Date and TitleCase Pipe
      All of which have distinct use case
      Title Case pipe is for transforming text to title case.
      Date Pipe is for formatting Dates value according to locale rules.
      Currency Pipe is for formatting currency based on local rules as well i.e Dollar format or PHP
      AsyncPipe is use for reading the value from a Promise or an RxJS Observable API's.
      Decimal Pipes are use to converting a number string to decimal format based on the locale settings
      I18nPluralPipe is used for pluralizing the string according again, to locale settings
      I18nSelectPipe is like converting value to another value, transforming so to speak in the example we use gender
      JsonPipe is for transforming an object '{}' into a json format.
      KeyValuePipe simply comverts a map or object into key value pairs
      LowerCasePipe simply transforms text to all lower case.
      PercentPipe transforms a number to a percentage string, formatted according to locale rules.
      SlicePipe is similar to array slicing: creates a new Array or String containing a subset (slice) of the elements.
      UpperCasePipe transforms all character into uppercase
      */
      imports: [
        AsyncPipe, CurrencyPipe, DatePipe, DecimalPipe, I18nPluralPipe, 
        I18nSelectPipe, JsonPipe, KeyValuePipe, LowerCasePipe, PercentPipe, 
        SlicePipe, TitleCasePipe, UpperCasePipe
      ],
      template: `
        <main>
          <h1>Angular Pipes Showcase</h1>

          <h2>AsyncPipe</h2>
          <p>Async data: {{ asyncData | async }}</p>

          <h2>CurrencyPipe</h2>
          <p>Amount: {{ amount | currency:'USD' }}</p>

          <h2>DatePipe</h2>
          <p>Current date: {{ currentDate | date:'full' }}</p>

          <h2>DecimalPipe</h2>
          <p>Pi: {{ pi | number:'1.2-5' }}</p>

          <h2>I18nPluralPipe</h2>
          <p>{{ messageCount | i18nPlural: messageMapping }}</p>

          <h2>I18nSelectPipe</h2>
          <p>{{ gender | i18nSelect: genderMapping }}</p>

          <h2>JsonPipe</h2>
          <pre>{{ objForJson | json }}</pre>

          <h2>KeyValuePipe</h2>
          <ul>
            <li *ngFor="let item of objForKeyValue | keyvalue">
              {{item.key}}: {{item.value}}
            </li>
          </ul>

          <h2>LowerCasePipe</h2>
          <p>{{ mixedCaseText | lowercase }}</p>

          <h2>PercentPipe</h2>
          <p>{{ percentage | percent:'2.2-4' }}</p>

          <h2>SlicePipe</h2>
          <p>{{ longText | slice:0:20 }}...</p>

          <h2>TitleCasePipe</h2>
          <p>{{ titleText | titlecase }}</p>

          <h2>UpperCasePipe</h2>
          <p>{{ lowerCaseText | uppercase }}</p>
        </main>
      `,
    })
    export class AppComponent {
      asyncData: Observable<string> = of('This is async data');
      amount = 123.45;
      currentDate = new Date();
      pi = Math.PI;
      messageCount = 3;
      messageMapping: {[k: string]: string} = {
        '=0': 'No messages.',
        '=1': 'One message.',
        'other': '# messages.'
      };
      gender = 'female';
      genderMapping: {[k: string]: string} = {
        'male': 'He',
        'female': 'She',
        'other': 'They'
      };
      objForJson = { name: 'John', age: 30 };
      objForKeyValue = {
        id: 1,
        name: 'Angular',
        version: 14
      };
      mixedCaseText = 'ThIs Is MiXeD cAsE tExT';
      percentage = 0.7589;
      longText = 'This is a very long text that will be sliced using the SlicePipe';
      titleText = 'this is a title';
      lowerCaseText = 'this will be transformed to upper case';
    }

Creating a Custom Pipe

  • We can create a custom pipe by using @Pipe Directive in the angular file with a combination of extending the class implementing the PipeTransform interface, here we’ll take a closer look at how to do it in the custom pipe kebab case transformer provided by Angular Documentation:

      // kebab-case.pipe.ts
      import { Pipe, PipeTransform } from '@angular/core';
      @Pipe({
        name: 'kebabCase',
        standalone: true,
      })
    
      // Here we're creating a class that has a contract with PipeTransform interface
      export class KebabCasePipe implements PipeTransform {
          // This is the place where magic happens
          // We're creating a function called transform that is abstracts by the PipeTransform interface
          // trnasform here has a parameter value of type string and returns string as well
        transform(value: string): string {
        // Here the value parameter undergo to method chain, transforming it to lowercase then replacing space with '-'
          return value.toLowerCase().replace(/ /g, '-');
        }
      }
    
T

Excellent

2 Days Late

More from this blog