Skip to main content

Understanding Angular Pipes

“A pipe is a way to write display-value transformations that you can declare in your HTML. It takes in data as input and transforms it to a desired output”.
Angular Pipes definition is pretty straight forward and realising that they can be very useful as well. Angular comes with some helpful built-in pipes that are ready for use and also allows us to create our own custom pipes; and we are going to dive into it here.

Built-in Pipes

Angular comes with a set of pipes, which are available for use in any template. We are now going to see some of the most useful and how to use them. Our expectation here is not only to allow us to use them in our Angular applications but also help us understand how they work.
It formats a date value to a string, formatted according to provided parameters.
const value = new Date('2019-03-01');<p>Birthdate: {{ value | date : 'dd/MM/YYYY' }}</p><!-- output '01/03/2019' -->
Input: a Date object, a number (ms since UTC epoch) or an ISO string;
Parameter: Date Format;
You can check all formatting options here:https://angular.io/api/common/DatePipe
It transforms a number value to a percentage string, formatted according to provided parameters.
const value = 23.1;<p>Percentage: {{ value | percent : '3.2-2' }}</p><!-- output '023,10%' -->
Input: a number;
Parameters:
  • minIntegerDigits: The minimum number of integer digits before the decimal point. Default is 1 ;
  • minFractionDigits: The minimum number of digits after the decimal point. Default is 0 ;
  • maxFractionDigits: The maximum number of digits after the decimal point. Default is 0 .
It transforms a string into a substring of it or an array into a subset of it.
const value = 'Leonardo';<p>Nickname: {{ value | slice : 0 : 2 }}</p><!-- output 'Leo' -->--------------------------------------------------const values = ['Red', 'Blue', 'Green', 'Purple'];<p>Colors:</p>
<ul>
  <li *ngFor="let value of values| slice : 1 : 3" >
    {{ value }}
  </li>
</ul><!-- output 
  <ul>
    <li>Blue</li>
    <li>Green</li>
  </ul>
-->
Input: an array or a string;
Parameters:
  • startnumber: the starting index of the subset to return;
  • endnumber: the ending of the subset to return.
It transforms a string to all lower case or to all uppercase.
const value = 'Leonardo';<p>In Lowercase: {{ value | lowercase }}</p><!-- output 'leonardo' --><p>In Uppercase: {{ value | uppercase }}</p><!-- output 'LEONARDO' -->
Input: a string.

Custom Pipes

Sometimes you may need specific transformations, in which the default Angular Pipes won’t be enough. That’s when Custom Angular Pipes take place, which allows you to create your own pipe, specifying the input, the transformation function and the output.
First we are going to create our pipe. This will be a very simple one just for explanation, in which we are going to provide a string parameter which is going to be concatenated to a Hello. We do it like the following:
import { Pipe, PipeTransform } from '@angular/core';@Pipe({
  name: 'sayHello'
})
export class GreetingsPipe implements PipeTransform {  public transform(name: string): string {
    return 'Hello, ' + name;
  }}
The name specified in the @Pipe decorator is the name of the pipe that will be used in the HTML, like datelowercaseuppercase, etc.
The transform function is where the magic happens, where you actually do the desired transformation on the received input. On the example above, we are receiving one input parameter (a name string), which is the value which we are going to apply the transform function. The first parameter in the transform function is always the value we are going to work with.
However we can receive as many parameters as we’d like, in case we need themn. We would then provide them in the HTML and be able to use them in the transform function, as we are going to see further. Finally, our transform function returns a string, which is going to be our pipe’s output.
Then, in order to use it we are going to register it. To register a Pipe, all you have to do is add its class to a module declarations. Here we are also going to create a module for that pipe and export it to be used in other modules.
import { NgModule } from '@angular/core';
import { GreetingsPipe } from './greetings.pipe';@NgModule({
   declarations: [
     GreetingsPipe
   ],
   exports: [
     GreetingsPipe
   ]
})
export class GreetingsPipeModule { }
Once you have your pipe created, registered in a module and have that module imported where you will need it, your pipe is ready to be used!
Supposing we have an user object in our component with a property firstName,which is a string containing the user’s first name. Then, we could add to our HTML a paragraph to greet our user, like shown bellow:
this.user = {
  firstName: 'Leonardo',
  ...
};--------------------------------------------------<div>
  <p>You are now logged in our application!</p>
  <p>{{ user.firstName | sayHello }}</p>
</div><!-- output
  <p>Hello, Leonardo</p>
-->

Custom Pipes Examples

Now we are going to see some more realistic pipe examples, which could be used in real world applications.
Firstly, it is important to notice that Angular does have a built-in CurrencyPipe which you can use. However, I wanted to show how to build one in case you need some specific formatting of your own and for learning purposes.
So let’s say I want this: 105.5 > R$ 105,50
import { Pipe, PipeTransform } from '@angular/core';@Pipe({
  name: 'currencyFormat'
})export class CurrencyFormat implements PipeTransform {  public transform(
    value: number,
    currencySign: string = 'R$ ',
    chunkDelimiter: string = '.',
    decimalDelimiter: string = ','
  ): string {    if (!value)
      return currencySign + '0' + decimalDelimiter + '00';    const changedValue = this.addCommas(value.toFixed(2));
    const formatted = changedValue.toString().replace(
      /[,.]/g, function (val) {
        return val === ',' ? chunkDelimiter : decimalDelimiter;
      }
    );    return currencySign + formatted;
  }  private addCommas(nStr) {
    nStr += '';
    const x = nStr.split('.');
    let x1 = x[0];
    const x2 = x.length > 1 ? '.' + x[1] : '';
    const rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
  }
}
As I had said previously, you can receive as many input params as necessary, which is the case in our currencyFormatpipe. The first parameter is the value we are going to format itself. However, we are also receiving here the currencySign (string), the chunkDelimiter (string) and the decimalDelimiter (string), so we could use them in our transformfunction. And this is how we would use our pipe:
{{ 9999.9 | currencyFormat : 'R$' : '.' : ',' }}<!-- output: R$ 9.999.90 -->
In Brazil, every person has a document named CPF, which is a unique number with specific formatting. Sometimes, we need to output the value of a document formatted correctly by receiving a raw string with its value.
So what we want is this: 11111111111 -> 111.111.111–11
import { Pipe, PipeTransform } from '@angular/core';@Pipe({
  name: 'cpfFormat'
})
export class CpfFormat implements PipeTransform {  public transform(cpf: string): string {
    if (!cpf || cpf.trim() === '') { return ''; }
    let formatted: string;
    formatted = cpf.substring(0, 3) + '.';
    formatted = formatted + cpf.substring(3, 6) + '.';
    formatted = formatted + cpf.substring(6, 9) + '-';
    formatted = formatted + cpf.substring(9, 11);
    return formatted;
  }}
Here the pipe is much simpler. We don’t need any other parameter but the value itself, since the formatting of a CPF is a defined pattern. We receive an unformatted CPF string and return the formatted CPF string. And this is how we would use our pipe:
{{ '99999999999' | cpfFormat }}<!-- output: 999.999.999-99 -->

Extra: Testing Pipes

Creating Unit Tests for Custom Pipes are quite simple since they are basically pure functions; that receive an input and return a desired output. Below, I have an example on creating a simple test for the CPF Pipe created before.
import { CpfFormat } from './cpf.pipe';describe('[Pipe] CPF Format', () => {   let pipe: CpfFormat;  beforeEach(() => {
    pipe = new CpfFormat();
  });   it('should return a valid \'cpf\' formatted correctly', () => {
    expect(pipe.transform('32726532950')).toBe('327.265.329-50');
  });  it('should return empty for a null \'cpf\'', () => {
    expect(pipe.transform(null)).toBe('');
    expect(pipe.transform('')).toBe('');
  });});

Angular Pipes are a very simple but useful functionality provided by Angular, which is almost certain to be used a lot throughout applications. Therefore it is important to know your way around them and be able to efficiently use them to fit your needs.

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...