Tue Nov 24 2015
Paul Shan
Angular 2.0 is still beta (I’m using beta.1 here). If you find any difficulties to implement those what's written in the article (though I will try to keep the article updated always), please post a comment about that.
In the series of our AngularJs 2.0 tutorials, today is the time for pipes. Pipes are the modernized version of filters in Angular 1.X. Something like using function in your templates; or something like helpers to modify, choose, format your value within the template.
Pipes don’t give you any new feature. In angular 2 you can use logics in templates too. You also 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.
myValue | myPipe:param1:param2 | mySecondPipe:param1
The pipe expression starts with the value followed by the symbol pipe (|), than the pipe name. The params for that particular pipe can be sent separated by colon (:) symbol. The order of execution is from left to right. However the pipe operator only works in your templates and not in JavaScript code. In JavaScript the pipe symbol works as bitwise operator.
Examples are always best things to understand anything about programming. Below are three different examples of pipes and their descriptions.
{{"Paul Shan" | lowercase}}
Output >> paul shan
lowercase is a predefined pipe. In the given example, the string “Paul Shan” is passed as a value to the pipe lowercase, and the output paul shan is returned.
import {Component, View} from 'angular2/core'; @Component({ selector: 'date-pipe', }) @View({ template: `Pipe Example
1. Today is {{today}}
2. Today is {{today | date}}
3. Today is {{today | date:"dd/MM/yyyy"}}
` }) export class DatePipe { today = new Date(); }
The pipe date is also a predefined date. The date format string we provided after colon is a parameter for the pipe date.
Though there are few predefined pipes available, but custom pipes are very much necessary; even that’s why the pipes exist. Below is an example of creating and using a custom pipe.
//file name: remove-spaces.ts import {Pipe} from "angular2/core"; @Pipe({ name : "removeSpaces" }) export class RemoveSpaces{ transform(value){ return value.replace(/ /g, ""); } }
import {Component, View} from 'angular2/core'; import {RemoveSpaces} from './remove-spaces.ts'; @Component({ selector: 'remove-spaces-impl', }) @View({ pipes: [RemoveSpaces], template: `Custom pipe : removeSpaces
{{sampleString}} => {{sampleString | removeSpaces}}
` }) export class RemoveSpacesImpl { sampleString = "I love angular 2"; }
Pipe classes has three hooks.
constructor() is the normal constructor of the class, example of transform() is already given above. onDestroy() is called once the pipe is going to be destroyed. You can find an example of this later on in this article.
There are many predefined or inbuilt pipes available in Angular 2.0. You can find them below with examples.
import {Component, View} from 'angular2/core'; @Component({ selector: 'date-pipe', }) @View({ template: `Pipe Example
1. Today is {{today}}
2. Today is {{today | date}}
3. Today is {{today | date:"dd/MM/yyyy"}}
` }) export class DatePipe { today = new Date(); }
This pipe is used to display the date in a particular format. There are multiple predefined formats available; like, “medium”, “short”, “fullDate” etc. You also can use your own custom format string using “y” as year, “M” as month, “d” as date, “h” as hour, “m” as minute, “s” as second and many more. For a brief you can check angular’s official document on date pipe
import {Component, View} from 'angular2/core'; @Component({ selector: 'decimal-pipe', }) @View({ template: `Decimal Pipe Example
pi (no formatting): {{pi}}
pi (.5-5): {{pi | number:'.5-5'}}
pi (2.10-10): {{pi | number:'2.10-10'}}
pi (.3-3): {{pi | number:'.3-3'}}
` }) export class DecimalPipe { pi: number = 3.1415927; }
This pipe is used to formal a number. You can set a min and max length after the decimal point and a fixed number (or leave it blank for default) for the places before the decimal point.
import {Component, View} from 'angular2/core'; @Component({ selector: 'currency-pipe', }) @View({ template: `Currency Pipe Example
A in USD: {{a | currency:'USD':true}}
B in INR: {{b | currency:'INR':false:'4.2-2'}}
` }) export class CurrencyPipe { a: number = 0.12345; b: number = 1.09876; }
This pipe helps you to format and using the symbols as ISO 4217 currency code, such as “USD” for the US dollar and “EUR” for the euro. The second parameter it takes is symbolDisplay whose default value is false. The third parameter is digitInfo which works as DecimalPipe.
import {Component, View} from 'angular2/core'; @Component({ selector: 'case-pipe', }) @View({ template: `Lower and Upper case Pipe Example
In lowerCase : {{str | lowercase}}
In uppercase : {{str | uppercase}}
` }) export class LowerUpperCasePipe { str: string = "My name is Paul Shan"; }
The name says it all. These two pipes just changes the cases of the characters. They don’t accept any parameters.
import {Component, View} from 'angular2/core'; @Component({ selector: 'json-pipe', }) @View({ template: `JSON Pipe Example
Without JSON Pipe.
{{obj}}With JSON Pipe.
{{obj | json}} ` }) export class JSONPipe { obj: Object = { name: {fName: "Paul", lName:"Shan"}, site:"VoidCanvas", luckyNumbers:[7,13,69] }; }
Normally with the help of double curly brace operator ({{}}) you can print a value but not an entire object. You end up printing [object object]. To print the JSON object properly you can use JSONPipe.
import {Component, View} from 'angular2/core'; @Component({ selector: 'percent-pipe', }) @View({ template: `Percent Pipe Example
myNum : {{myNum | percent}}
myNum (3.2-2) : {{myNum | percent:'3.2-2'}}
` }) export class PercentPipe { myNum: number = 0.1415927; }
It converts the number in percentage and also adds the percentage symbol (%) after it.
import {Component, View} from 'angular2/core'; import {NgFor} from 'angular2/common'; @Component({ selector: 'slice-pipe', }) @View({ directives:[NgFor], template: `Slice Pipe Example
{{str}} (0:4): {{str | slice:0:4}}
names (1:4)
Slice pipe is a pipe which works just like JavaScript’s Array.prototype.slice().
import {Component, View} from 'angular2/core'; @Component({ selector: 'async-pipe', }) @View({ template: `Async Pipe Example
wait... {{promise | async}}
` }) export class AsyncPipe { promise : Promise= null; clickMe() { this.promise = new Promise ((resolve, reject) => { setTimeout(function () { resolve("resolved"); },2000); }); } }
This is one of the very interesting pipes. It works as an observer to a promise. If the promise is resolved.
Pipe also accepts a metadata called pure. The listed predefined pipes above are all pure pipes (the pure property is set to true). If a pipe is pure, it will re-execute only the value of the input or the passed parameter are changed. But if you want to re-run a pipe independently of the scenario I just said, you can make your pipe impure by setting the property pure to false.
@Pipe({name: 'countdown', pure: false}) class CountDown implements PipeTransform, PipeOnDestroy { remainingTime:Number; interval:SetInterval; onDestroy() { if (this.interval) { clearInterval(this.interval); } } transform(value: any, args: any[] = []) { if (!parseInt(value, 10)) return null; if (typeof this.remainingTime !== 'number') { this.remainingTime = parseInt(value, 10); } if (!this.interval) { this.interval = setInterval(() => { this.remainingTime-=50; if (this.remainingTime <= 0) { this.remainingTime = 0; clearInterval(this.interval); delete this.interval; } }, 50); } return this.remainingTime; } } @Component({ selector: 'impure-pipe', }) @View({ pipes: [CountDown], directives: [NgIf], template: `` }) export class ImpurePipe { active:boolean = false; toggleActiveState() { this.active = !this.active; } }Impure pipe
A counter with setInterval()
{{ 10000 | countdown }}
This code is another use of custom pipes. A custom pipe countdown is created, setting the pure property to false. It has a timer inside it which runs in every 50 milliseconds and changes the value of a certain property of the pipe.
Angular 1.X had a concept of filters. Pipes are very much similar to that but it has some significant advantages, the pipes.
Filters used to act like helpers, very similar to functions where you pass the input and other parameters and it returns you the value; but pipe works as a operator. The concept is, you have an input and you can modify the input applying multiple pipes in it. This not only simplifies the nested pipe logic, but also gave you a beautiful and clean syntax for your templates. Secondly, in case of async operations, you need to set things manually in case of angular 1.X filters. But pipes are smart enough to handle async operations
SHARE THIS ARTICLE
Thu Mar 10 2016
OAuth authentications are pretty popular now a days and another thing which is popular is JavaScript. This article shows how to plugin google’s oAuth api for authentication in your own node application.Sat Mar 01 2014
This is a continuation of my CSS3 loader snippet collection series. I've provided spinning css3 animation loader in the part 1 of this series and here in part 2, I'm providing various square type loading