Angular 2 Pipes

Introduction

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.

Prior to Angular 2, text transformation was provided by “filters”. Conceptually the same in usage, Angular 2 gives us a little more power and flexibility to how we can package up the text manipulation power of these smaller components.

Commonly used & built in Pipe examples

Some pipes merely intake a string and return a formatted result, others take parameters to help construct the resulting output.

The best part of using these are literally built into the framework. No extra file library inclusions are required.

UpperCasePipe & LowerCasePipe

UpperCasePipe & LowerCasePipe are two built in pipes that allow you to transform text, as their names would imply, before outputting to the DOM.

These are the most simple of pipes (and really, could be replace with some CSS) but they illustrate the mechanic: The value you wish to transform goes on the left a “pipe” (this “|” character) and then the transformative function goes on the right.

Here are two quick examples:

<p>{{ firstname | lowercase }}</p> // Foo -> foo 
<p>{{ lastname | uppercase }}</p> // Foo -> FOO 

Pretty simple, and lets us explain some more complex setups.

DatePipe & CurrencyPipe

There are also some slightly more complex built in pipes, some of which take in full objects, other take expressions from which to transform the text they transform.

DatePipe

DatePipe formats and transforms a Date object into a string based on a provided expression and locale rules.

Here are some example DatePipe usages with some of the build in expressions:

<p>{{ now | date }}</p> // Nov 15, 2016 
<p>{{ now | date:'medium' }}</p> // Nov 15, 2016, 12:05:08 PM 
<p>{{ now | date:'M-d-y' }}</p> // 11-15-16

CurrencyPipe

Like the DataPipe, CurrencyPipe also formats using a provided express and based on the browser’s locale. I’ll leave you to check the official documentation, but this is a very basic example.

<p>Total: {{ total | currency:'USD':true:'4.2-2'}}</p> // $10.99

Creating Custom Pipes

Creating custom pipes can be a little scary and intimidating at first, but is not hard in principle. We’ll walk you through the basics and provide a few examples to work from.

Structure and formatting your Pipe definition

Creating a pipe is pretty easy, in fact it looks like how you create an angular component. Let’s break down this example:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'foobar'})
export class FooBarPipe implements PipeTransform {
 
    transform(value: string, args: string[]): any {
        return "FooBar" + value;
    }
 
}

After including the Pipe & PipeTransform libraries from angular/core, you simply need to use the @Pipe decorator. The decorator accepts a parameter called “name” which is used to reference your custom pipe in your template code.

Finally, your pipe must implement a method called “transform” which, coincidentally, transforms your provided text or object.

And including into your app module is also quite simple:

import { FooBarPipe } from './foobar.pipe';

...

@NgModule({
 imports: [ BrowserModule ],
 declarations: [ App, FooBarPipe ],
 bootstrap: [ App ]
})
export class AppModule {}

Parameters

As we noted previously, you can also pass parameters to a pipe to affect the how the value piped in is transformed. You can send multiple parameters as well each separated by a colon (“:”) and extract them in your transform method.

Example 1: Prefix “FooBar” to a provided string

This is a simple example of a custom pipe that prefixes “FooBar”:

Example 2: Multiply a provided integer by Number

Show an example where we multiply the output by 42 (provided by the component) and return a result. This will illustrate the idea of stateful pipes.

Example 3: Convert string to Pig Latin

Here is an example of a pipe that converts a provided string to Pig Latin.

Conclusion

Pipes are a useful and easy to learn concept in angular 2. While it’s easy to think they are limited to formatting and displaying text, we have also shown some re-usable examples where a company can have a small arsenal of pipes at their disposal.

Next Post

Comments

See how we can help

Lets talk!

Stay up to date on the latest technologies

Join our mailing list, we promise not to spam.