Angular Pipes

  • Angular pipes are used for transforming data like dates, strings, currency, etc.
  • Pipes accepts input values and return the transformed value.
  • We can create custom pipes which can be used through out the application.
  • To apply a pipe, use the pipe operator (|) within a template expression

Below are few built-in pipes used for data formatting.

  • DatePipe – formats a date value
  • CurrencyPipe : Transforms a number to a currency string which is formmatted to the locale which we provide as input.
  • LowerCasePipe: Transforms text to lower case
  • UpperCasePipe: Transforms text to upper case

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',  
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  todayDate?: Date;
  dateOfBirth?: Date;

  constructor() {
    this.todayDate = new Date();
    this.dateOfBirth = new Date(1986,6,25);// July 25th 1986
   }
}

app.component.html

<h2>Date Pipes Examples</h2>
<table>
  <tr>
    <th>Date Format</th>
    <th>Output</th>
  </tr>
  <tr>
    <td>Default</td>
    <td>{{todayDate | date}}</td>
  </tr>
  <tr>
    <td>Short </td>
    <td>{{todayDate | date:'short'}}</td>
  </tr>
  <tr>
    <td>Medium</td>
    <td>{{todayDate | date:'medium'}}</td>
  </tr>
  <tr>
    <td>Long</td>
    <td>{{todayDate | date:'long'}}</td>
  </tr>
  <tr>
    <td>Full Date</td>
    <td>{{todayDate | date:'fullDate'}}</td>
  </tr>

</table>
<h2>Currency Pipes Examples</h2>

<b>{{123456.78 | currency:"USD"}}</b><br/>
<b>{{123456.78 | currency:"INR"}}</b><br/>

<h2>Lowercase and Uppercase Pipes Examples</h2>

<b>{{"Venkataramana" | lowercase }}</b><br/>
<b>{{"Venkataramana" | uppercase}}</b><br/>

<h6>Date of Birth : {{dateOfBirth | date}}</h6> 

app.component.css

table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
  }
  th, td {
    padding: 5px;
  }
  th {
    text-align: left;
  }

Custom Pipes

  • We can create custom pipe for custom data transformations if the features we are looking not available in buit-in pipes.
  • Mark a class as a pipe and supply configuration metadata, apply the @Pipe decorator to the class and use name in the template expressions.
  • Include your custom pipe in the declarations field of the NgModule metadata to make it available to a template.
  • When you create pipe using Angular CLI (ng generate pipe <pipename>), it registers the pipe automatically.
  • Implement the PipeTransform interface in your custom pipe class to perform the transformation and angular invokes the transform method with the value of a binding as the first argument, and any parameters as the second argument in list form, and returns the transformed value.

mycustompipe.pipe.ts

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

@Pipe({
  name: 'mycustompipe'
})
export class MycustompipePipe implements PipeTransform {

   reverse(str:string) {
    return str.split('').reverse().join('');
  }

  isPalindrome(str:string) {
    return str.split('').reverse().join('') === str;
  }

 titleCase(str:any) {
  return str.toLowerCase().split(' ').map(function(message:any) {
    return message.replace(message[0], message[0].toUpperCase());
  }).join(' ');
}

  transform(value: string, args?: string): any {
    switch (args || null) {
      case 'titlecase':
        return this.titleCase(value)
      case 'reverse':
        return this.reverse(value)
      case 'ispalindrome':
        return this.isPalindrome(value)
      case 'uppercase':
        return value.toUpperCase();
      case 'lowercase':
        return value.toLowerCase();
      default:
        return value;
    }
  }
}

app.component.ts

import { Component } from '@angular/core';
import {MycustompipePipe} from './mycustompipe.pipe';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',  
  styleUrls: ['./app.component.css']
})
export class AppComponent{
  constructor() {
    
   }
  }

app.component.html

<p> {{"angular pipes"| mycustompipe:'titlecase'}}
<p> {{"angular pipes"| mycustompipe:'lowercase'}}
<p> {{"angular pipes"| mycustompipe:'uppercase'}}
<p> {{"pipes"| mycustompipe:'reverse'}}
<p> {{"121"| mycustompipe:'ispalindrome'}}

Calling Custom Pipes Inside Component Class

  • Import Custom Pipe
  • Add Custom Pipe to Providers inside @Component
  • Inject Custom Pipe into Constructor
  • Calling transform method
  • Passing Transformed data to HTML Page

app.component.ts

import { Component, OnInit } from '@angular/core';
import {MycustompipePipe} from './mycustompipe.pipe';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',  
  styleUrls: ['./app.component.css'],
  providers: [ MycustompipePipe ]

})
export class AppComponent implements OnInit {
  message?: any;
  constructor( private custompipe: MycustompipePipe) {
   }

  ngOnInit() {
    this.message = this.custompipe.transform('Venkataramana','lowercase');
    console.log(this.message);

}

}

app.component.html

<p> Transformed Pipe Data : {{message}}

Check our other Angular Tutorials at Angular Tutorials

References:

  • https://angular.io/guide/pipes

Learn more about Angular features in the upcoming Angular Blog articles.

Happy Learning!