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

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...