w3resource

Pipes

Generally, when we perform data transformation, we implement the transformation in our model, for example, we let's say we have a number 1423.46 and we want to display it such that it has a appears as a currency like so $1,423.56. we can convert the number into a string in the model but if the only place we want to show the above-stated effect is in a view, then use of pipes is advised.

Clearly, some values benefit from a bit of editing. You may notice that you desire many of the same transformations repeatedly, both within and across many applications. You can almost think of them as styles. In fact, you might like to apply them in your HTML templates as you do styles.

Angular pipe is a way to write display-value transformations that you can declare in your HTML.

Using pipes

A pipe takes in data as input and transforms it to the desired output. As a use case, we will use pipes to transform a component's birthday property into a human-friendly date.

HTML Code (Birthday message using pipe):

<p>
  My friend's birthday is {{ birthday | date }}
</p>

TypeScript Code (Birthday message using pipe):

import { Component } from '@angular/core';

@Component({
  selector: 'app-friend-birthday',
  template: `

My friend's birthday is {{ birthday | date }}

` }) export class HeroBirthdayComponent { birthday = new Date(1988, 3, 15); // April 15, 1988 }

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen pipes_birthdayExample.ts by w3resource (@w3resource) on CodePen.


Inside the interpolation expression, you flow the component's birthday value through the pipe operator (|) to the Date pipe function on the right. All pipes work this way.

Built-in pipes

Angular comes with a stock of pipes such as DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe, and PercentPipe. They are all available for use in any template.

Parameterizing a pipe

A pipe can accept any number of optional parameters to fine-tune its output. To add parameters to a pipe, follow the pipe name with a colon (:) and then the parameter value (such as currency:'EUR'). If the pipe accepts multiple parameters, separate the values with colons (such as slice:1:5)

Chaining pipes

You can chain pipes together in potentially useful combinations. In the following example, to display the birthday in uppercase, the birthday is chained to the DatePipe and on to the UpperCasePipe. The birthday displays as APR 15, 1988.

friend.html

The chained friend's birthday is {{ birthday | date | uppercase}}

This example-which displays FRIDAY, APRIL 15, 1988-chains the same pipes as abov but passes in a parameter to date as well.

friend.html

The chained hero's birthday is {{  birthday | date:'fullDate' | uppercase}}

Custom Pipes

You can write your own custom pipes. Here's a custom pipe named ExponentialStrengthPipe that can boost an avatar's powers:

TypeScript Code (exponential-strength.pipe.ts):

import { Pipe, PipeTransform } from '@angular/core';
/*
 * Raise the value exponentially
 * Takes an exponent argument that defaults to 1.
 * Usage:
 *   value | exponentialStrength:exponent
 * Example:
 *   {{ 2 | exponentialStrength:10 }}
 *   formats to: 1024
*/
@Pipe({name: 'exponentialStrength'})
export class ExponentialStrengthPipe implements PipeTransform {
  transform(value: number, exponent: string): number {
    let exp = parseFloat(exponent);
    return Math.pow(value, isNaN(exp) ? 1 : exp);
  }
}

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen pipes_custompipes by w3resource (@w3resource) on CodePen.


This pipe definition reveals the following key points:

A pipe is a class decorated with pipe metadata.

The pipe class implements the PipeTransform interface's transform method that accepts an input value followed by optional parameters and returns the transformed value.

There will be one additional argument to the transform method for each parameter passed to the pipe. Your pipe has one such parameter: the exponent.

To tell Angular that this is a pipe, you apply the @Pipe decorator, which you import from the core Angular library.

The @Pipe decorator allows you to define the pipe name that you'll use within template expressions. It must be a valid JavaScript identifier. Your pipe's name is exponentialStrength.

Below is the component that demonstrates the exponential-strength.pipe.ts

TypeScript Code:

import { Component } from '@angular/core';

@Component({
  selector: 'app-power-booster',
  template: `
    <h2>Power Booster</h2>
    <p>Super power boost: {{2 | exponentialStrength: 10}}</p>
  `
})
export class PowerBoosterComponent { }

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen custompipes_component.ts by w3resource (@w3resource) on CodePen.


Pure and impure pipes

@Pipe({
  name: 'myCustomPipe', 
  pure: false/true        <----- here (default is `true`)
})
export class MyCustomPipe {}

There are two categories of pipes: pure and impure. Pipes are pure by default. Every pipe you've seen so far has been pure. You make a pipe impure by setting its pure flag to false.

Pure pipes

Angular executes a pure pipe only when it detects a pure change to the input value. A pure change is either a change to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object).

Angular ignores changes within (composite) objects. It won't call a pure pipe if you change an input month, add to an input array, or update an input object property.

This may seem restrictive but it's also fast. An object reference check is fast—much faster than a deep check for differences—so Angular can quickly determine if it can skip both the pipe execution and view update.

For this reason, a pure pipe is preferable when you can live with the change detection strategy. When you can't, you can use the impure pipe.

Impure pipes

Angular executes an impure pipe during every component change detection cycle. An impure pipe is called often, as often as every keystroke or mouse-move.

With that concern in mind, implement an impure pipe with great care. An expensive, long-running pipe could destroy the user experience.

Previous: Attributes Directives
Next: Reactive Forms



Follow us on Facebook and Twitter for latest update.