“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.
DatePipe
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
PercentagePipe
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 is1
;minFractionDigits
: The minimum number of digits after the decimal point. Default is0
;maxFractionDigits
: The maximum number of digits after the decimal point. Default is0
.
SlicePipe
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.
Lowercase & Uppercase
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.
1. Creating a Custom Pipe
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 date, lowercase, uppercase, 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.
2. Registering a Custom Pipe
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 { }
3. Using a Custom Pipe
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.
Currency Pipe
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 -->
Document Format Pipe
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
Post a Comment