Pipes

When binding data on our HTML template, we might want to present the data in a different form rather than just the data itself (meaning that Angular will use the _toString method on the presented object).

Therefore, we can run the data through a pipe.The syntax for doing so is to add a pipe sign (|) after the binding expression and use a pipe.

We might add some more argument to the pipe using the colon mark (:) before each argument we add.

We will need, of course, to add the pipe’s type to our pipes array member of our component’s ViewMetaData after importing it.

Built in pipes

Here are some built in pipes, which all may be imported from ‘@angular/common’;

  1. UpperCasePipe (name: ‘uppercase’) returns an upper-case string
  2. LowerCasePipe (name: ‘lowercase’) returns a lowe-case string
  3. ReplacePipe (name: ‘replace’) receives pattern and replacement as arguments, returns a string after replacement is done. The pattern can be a string or a regualr expression, the replacement can be a string or a function
  4. DatePipe (name: ‘date’) receives pattern as argument and returns a formatted date according to the given pattern, or to the browser’s default locale if no pattern has been given

Writing custom pipes

A pipe is also a class, however, this class implements the PipeTransform interface that has a method named transform, which is the one who does the formatting work.

To demonstrate, here is a simple pipe that reverses its given source:

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

@Pipe({name: 'reverse'})
export class ReversePipe implements PipeTransform {

    transform(source:any) {
        if (!source || !source.length){
            return source;
        }
        let result = '';
        for (let i = 0; i < source.length; i++)
       {
          result+= s[s.length - i - 1];
       }
       return result;
    }
}

To use the pipe in our component we will import it, put its type in our pipes array on our ViewMetaData parameter sent to the Component decorator, and put its name wherever we need in our template.

/*Import the child component */

import {ReversePipe} from 'path/to/reversepipe';

@Component({selector: 'main-component',
template: `<h1>{{compoenntName}}</h1>
         <!-- and now in reverse -->
         <h2>{{compoenntName | reverse}}</h2>
         `

 pipes: [ReversePipe]
 })
 export class MainComponent{
     private componentName: string;

     constructor(){
      this.componentName = 'Main app component';
     }
 }

IN Next chapter you will learn about using Directives .