A guide to Angular's Pipes
So what exactly are pipes?
There's not much of a difference when we use the real world example of pipes to understand the angular's pipes. Well here's a sentence denoting real world pipe : He heard a tune being piped. Pretty straight forward huh? A person blows air (data) into a flute and controls (transforms) the music that comes out.
Well Angular's Pipes are no different, you give some input data and then transform the outcome of the same data but in a different format.
A deep dive into Angular Pipes
From the official Docs Pipes are : Pipes transform displayed values within a template.Pipes are a feature of Angular 2 that allows you to contextually manipulate and format text on the front end. From simple date formatting, to a complete transformation, pipes allow you to separate how you display data provided from the backend.
Usage can be as belows :
- You can display only some filtered elements from an array.
- You can modify or format the value.
- You can use them as a function.
- You can do all of the above combined.
Following are the in-built pipes provided by Angular.
Pipe Name | Angular |
---|---|
currency | ✓ |
date | ✓ |
uppercase | ✓ |
json | ✓ |
limitTo | ✓ |
lowercase | ✓ |
number | |
orderBy | |
filter | |
async | ✓ |
decimal | ✓ |
percent | ✓ |
General syntax
{{today | date }}
Pipe with Params
The pipe date is also a predefined date. The date format string we provided after colon is a parameter for the pipe date. Syntax {{today | date:"dd/MM/yyyy"}}
Code :
Date Pipe
Code :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component } from '@angular/core'; | |
@Component({ | |
selector: 'app-root', | |
template : ` | |
<h2>Pipe Example</h2> | |
<h4>1. Today is {{today}}</h4> | |
<h4>2. Today is {{today | date}}</h4> | |
<h4>3. Today is {{today | date:"dd/MM/yyyy"}}</h4> | |
` | |
}) | |
export class AppComponent { | |
today : Date; | |
constructor(){ | |
this.today = new Date(); | |
} | |
} |
Ouput :
1. Today is Wed May 24 2017 11:00:33 GMT+0530 (IST)
2. Today is May 24, 2017
3. Today is 24/05/2017
Decimal Pipe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Component} from '@angular/core'; | |
@Component({ | |
selector: 'decimal-pipe', | |
template: ` | |
<h2>Decimal Pipe Example</h2> | |
<p>pi (no formatting): {{pi}}</p> | |
<p>pi (.5-5): {{pi | number:'.5-5'}}</p> | |
<p>pi (2.10-10): {{pi | number:'2.10-10'}}</p> | |
<p>pi (.3-3): {{pi | number:'.3-3'}}</p> | |
` | |
}) | |
export class DecimalPipe { | |
pi: number = 3.1415927; | |
} |
Output :
pi (no formatting): 3.1415927
pi (.5-5): 3.14159
pi (2.10-10): 03.1415927000
pi (.3-3): 3.142
Currency Pipe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Component} from '@angular/core'; | |
@Component({ | |
selector: 'currency-pipe', | |
template: ` | |
<h2>Currency Pipe Example</h2> | |
<p>A in USD: {{a | currency:'USD':true}}</p> | |
<p>B in INR: {{b | currency:'INR':false:'4.2-2'}}</p> | |
` | |
}) | |
export class CurrencyPipe { | |
a: number = 0.12345; | |
b: number = 1.09876; | |
} |
Output :
A in USD: $0.12
B in INR: INR0,001.10
Upper Case Lower Case Pipe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Component} from '@angular/core'; | |
@Component({ | |
selector: 'case-pipe', | |
template: ` | |
<h2>Lower and Upper case Pipe Example</h2> | |
<p>In lowerCase : {{str | lowercase}}</p> | |
<p>In uppercase : {{str | uppercase}}</p> | |
` | |
}) | |
export class LowerUpperCasePipe { | |
str: string = "My name is Paul Shan"; | |
} |
Output :
In lowerCase : my name is paul shan
In uppercase : MY NAME IS PAUL SHAN
JSON Pipe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Component} from '@angular/core'; | |
@Component({ | |
selector: 'json-pipe', | |
template: ` | |
<h2>JSON Pipe Example</h2> | |
<h4>Without JSON Pipe.</h4> | |
{{obj}} | |
<h4>With JSON Pipe.</h4> | |
{{obj | json}} | |
` | |
}) | |
export class JSONPipe { | |
obj: Object = { name: {fName: "Paul", lName:"Shan"}, site:"VoidCanvas", luckyNumbers:[7,13,69] }; | |
} |
Output :
Without JSON Pipe.
[object Object]
With JSON Pipe.
{ "name": { "fName": "Paul", "lName": "Shan" }, "site": "VoidCanvas", "luckyNumbers": [ 7, 13, 69 ] }
Percent Pipe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Component} from '@angular/core'; | |
@Component({ | |
selector: 'percent-pipe', | |
template: ` | |
<h2>Percent Pipe Example</h2> | |
<p>myNum : {{myNum | percent}}</p> | |
<p>myNum (3.2-2) : {{myNum | percent:'3.2-2'}}</p> | |
` | |
}) | |
export class PercentPipe { | |
myNum: number = 0.1415927; | |
} |
Output :
myNum : 14.159%
myNum (3.2-2) : 014.16%
Slice Pipe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Component} from '@angular/core'; | |
@Component({ | |
selector: 'slice-pipe', | |
template: ` | |
<h2>Slice Pipe Example</h2> | |
<p>{{str}} (0:4): {{str | slice:0:4}}</p> | |
<h4>names (1:4)</h4> | |
<ul> | |
<li *ngFor="var name of names | slice:1:4">{{name}}</li> | |
</ul> | |
` | |
}) | |
export class SlicePipe { | |
str: string = "voidcanvas.com"; | |
names: string[] = ['paul', 'david', 'ean', 'renee', 'chloe'] | |
} |
Output :
voidcanvas.com (0:4): My n
names (1:4)
david
ean
renee
Async Pipe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Component} from '@angular/core'; | |
@Component({ | |
selector: 'async-pipe', | |
template: ` | |
<h2>Async Pipe Example</h2> | |
<p>wait... {{promise | async}}</p> | |
<button (click)="clickMe()">Click me to initiate promise</button> | |
` | |
}) | |
export class AsyncPipe { | |
promise : Promise <string> = null; | |
clickMe() { | |
this.promise = new Promise<string>((resolve, reject) => { | |
setTimeout(function () { | |
resolve("resolved"); | |
},2000); | |
}); | |
} | |
} |
Ouput :
wait...
Click me to initiate promise
wait... resolved
Click me to initiate promise
Custom Pipes
Though there are few predefined pipes available, but custom pipes are very much necessary; even that’s why the pipes exist.
You might have noticed Pipes is not a feature.You can execute a function in the template to get its returned value. But pipes is a handsome way to handle these things in templates. It makes your code more clean and structured.
Code :
Creating a custom pipe
Consuming the created custom pipe
You might have noticed Pipes is not a feature.You can execute a function in the template to get its returned value. But pipes is a handsome way to handle these things in templates. It makes your code more clean and structured.
Code :
Creating a custom pipe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Pipe} from "@angular/core"; | |
@Pipe({ | |
name : "trimWhiteSpaces" | |
}) | |
export class TrimWhiteSpaces{ | |
transform(value){ | |
return value.replace(/ /g, ""); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Component, View} from '@angular/core'; | |
import {TrimWhiteSpaces} from './whitespace.trim.pipe.ts'; | |
@Component({ | |
selector: 'remove-spaces-impl', | |
}) | |
@View({ | |
pipes: [TrimWhiteSpaces], | |
template: ` | |
<h2>Custom pipe : removeSpaces</h2> | |
<h4> {{sampleString}} => {{sampleString | trimWhiteSpaces}}</h4> | |
` | |
}) | |
export class RemoveSpacesImpl { | |
sampleString = "Angular Loves Bootstrap 3"; | |
} |
Pipe classes has three hooks.
- constructor(arguments)
- transform(value, arguments)
- onDestroy()
Pure Vs Impure Pipes
Pure pipes execute only on value change whereas impure pipes execute repeatedly on a user based scenario instead of value change. By default all Pipes provided by Angular as Pure Pipe. To make a custom pipe impure we simply set its metadata attribute to true Syntax @Pipe({name: 'custom', pure: false}).
Comments
Post a Comment