Formatting Data in Angular Templates with Pipes

Pipes used to be called filters in AngularJS. They're used for transforming data within your views, and can be used in any template expression. The basic syntax of a pipe looks like this: {{ total | currency:'USD' }} where total is the data we're transforming, currency is the name of the pipe performing the transformation, and 'USD' is an additional parameter that we're passing into the currency pipe.

Let's take a look at how we can create our own pipes using Angular:


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

@Pipe({ name: 'capitalize' })
export class CapitalizePipe implements PipeTransform {
  transform(text: string, numLetters: number) {
    if (numLetters === undefined) {
      return text.toUpperCase();
    } else {
      return (
        text.substring(0, numLetters).toUpperCase() +
        text.substring(numLetters, text.length)

The @Pipe() decorator takes two options, name as a string and pure as a boolean. Pure pipes only get re-evaluated when the input (the left hand of the pipe) changes. By default pipes are pure when the option is not specified. The PipeTransform interface enforces that we have the transform function defined on our class properly. The pipe we just made can take an optional parameter which specifies the number of letters in the string to capitalize.

Now lets have AppComponent use the CapitalizePipe we just made:


import { Component } from '@angular/core';
import { CapitalizePipe } from './capitalize.pipe';

  selector: 'my-app',
  template: '{{ message | capitalize }}',
  pipes: [CapitalizePipe]
export class AppComponent {
  message: string = 'Hello world!';

View the example live:

We can also pass in an additional parameter to captialize by changing our template to {{ message | capitalize:5 }} to capitalize the first 5 letters of the message.


I finished! On to the next chapter