Angular 2 pipes in depth; with list of inbuilt pipes and examples

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.

Usage of pipes

  • 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.

Why pipes?

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.

General syntax

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.

Example repo

My github repo contains all kind of examples of Angular 2.0. Pipe specific examples can be found here. You can download or clone the entire repo and using modules like *serve*, *live-server* or any other hosting tools, you can host and view the live examples.

Describing with examples

Examples are always best things to understand anything about programming. Below are three different examples of pipes and their descriptions.

Most simple pipe

{{"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.

Pipe with param

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.

Create a custom pipe

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.

designing the pipe

//file name: remove-spaces.ts
import {Pipe} from "angular2/core";

@Pipe({
	name : "removeSpaces"
})

export class RemoveSpaces{
	transform(value){
		return value.replace(/ /g, "");
	}
}

using the pipe

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"; }

hooks

Pipe classes has three hooks.

  • constructor(arguments)
  • transform(value, arguments)
  • onDestroy()

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.

All predefined pipes

There are many predefined or inbuilt pipes available in Angular 2.0. You can find them below with examples.

DatePipe

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

DecimalPipe

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.

CurrencyPipe

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.

LowerCasePipe & UpperCasePipe

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.

JSONPipe

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.

PercentPipe

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.

SlicePipe

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)

  • {{name}}
` }) export class SlicePipe { str: string = "voidcanvas.com"; names: string[] = ['paul', 'david', 'ean', 'renee', 'chloe'] }

Slice pipe is a pipe which works just like JavaScript’s Array.prototype.slice().

Async pipe

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.

Pure and Impure pipes

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: `
    

Impure pipe

A counter with setInterval()


{{ 10000 | countdown }}
` }) export class ImpurePipe { active:boolean = false; toggleActiveState() { this.active = !this.active; } }

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.

Pipe vs filter

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

post-thumbnail
Today everyone knows the importance of a lightning-fast website and how the speed impacts the conversion rate of a business. Today, everyone wants the site to be a PWA so that the mobile users can have an app-like experience with the website because, for the majority of the merchants, the customers come through mobile devices.
Tue Apr 20 2021
post-thumbnail
Here we are going to see how you can manage backup and restore of Postgres database with docker.
Thu Sep 03 2020
post-thumbnail
Image sliders or carousels always have increased the UI attraction of websites and they are pretty useful for reflecting the major roles/products too. In case, I am having a website that sells tee-shirts,
Mon Apr 30 2018

About VoidCanvas

This blog was created out of hobby and talks mostly about technology, web development, JavaScript, NodeJS and related topics. Thank you for reading my blog.

Copyright 2022 - www.voidcanvas.com

Popular Articles

Authentication using Google's oAuth api with node.js

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.

CSS3 Loader Snippet Collection: (Part 2 - Squares)

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