Learning Angular Pipes – Part I

Use pipes to create reusable data transformations.

Kelvin Yan

PUBLISHED:

What do Angular pipes do and when should one use them?

Pipes are an Angular feature that allow you to transform output inside your template. They transform your data once they are rendered on your screen.

Sometimes data from APIs or some other source may need fine tuning to be viewed attractively. We would have to write functions to transform properties and values into something cleaner and more readable for the user. Alternatively, if the data was from your own backend, you could format the data coming from the API as well, but there may be a good reason already for your data to be returned the way it is.

Angular Pipes give you the flexibility to transform data in the view without changing the actual data values themselves.

Pipes are one of the tools to make that easy for the developer. It is one of the excellent features of the Angular framework because of its clean style and the data-view transformations are declared on the HTML template data-bindings. If this seems useful to you, continue reading on to see how you can easily integrate pipes in your Angular projects.

Using pipes should be familiar to most developers as they are used often in Linux scripting and PowerShell.

Use Angular pipes by declaring the variable, followed by the pipe symbol “|” inside the HTML template.

Example syntax for adding a pipe: {{ myVariable | pipeName }}

There can be multiple pipes in a template and you can also chain pipes together. The Angular Framework provides several pipes already, but you can create custom pipes as well.

The use of pipes is to keep raw data separate from view data so that we only transform the viewed data as we need it.

The tutorial below shows examples in how to use Angular pipes. I assume you have some basic experience with Angular, so certain aspects of the code are not discussed in depth, such as ngFor and FormsModule. There is a introductory tutorial that is highly recommended, Tour of Heroes, to get you get started on Angular.

Tutorial — Purrfect Delivery Company

Imagine we are requesting data from an external pet store API, which calls a database and returns a list of kittens that are available for sale, as well as some additional details about each kitten.

To simplify the tutorial so that we can focus on pipes and the view, we will just hard code the data and assume it is being returned from an actual API.

Here is our JSON data that we receive from this pet store API.

{
  "kittens": [{
      "breed": "tabby",
      "name": "zeus",
      "birthdate": "2016-07-09",
      "price": 50
    },
    {
      "breed": "sphinx",
      "name": "charles",
      "birthdate": "2017-08-05",
      "price": 200
    }
  ] 
}

Now we use this JSON object to create a list for our kittens app in the template.

<h1>
  Kittens
</h1>
<div *ngFor="let kitten of petStoreData.Kittens">
  <ul><label>Breed:</label> {{ kitten.breed }}</ul>
  <ul><label>Name:</label> {{ kitten.name }}</ul>
  <ul><label>Birthdate:</label> {{ kitten.birthdate }}</ul>
  <ul><label>Price:</label> {{ kitten.price }}</ul>
</div>
Our kitten list viewed with raw data from the API.

Although this is satisfactory, we could improve the data being viewed in 4 ways:

  1. Breed is important to customers who are shopping our site so we should emphasize it by making it uppercase.
  2. Kitten’s name should have its first letter capitalized.
  3. Let’s convert the date of birth to age in months.
  4. Let’s add in currency conversion functionality for our global customers.

Starting off, Angular includes some pipes already built into the framework. Here we can use Angular’s UpperCasePipe. The list of featured pipes can be found here.

<h1>
  Kittens
</h1>
<div *ngFor="let kitten of petStoreData.Kittens">
  <ul><label>Breed:</label> {{ kitten.breed | uppercase }}</ul>
  <ul><label>Name:</label> {{ kitten.name }}</ul>
  <ul><label>Birthdate:</label> {{ kitten.birthdate }}</ul>
  <ul><label>Price:</label> {{ kitten.price }}</ul>
</div>

We use the pipe symbol “|” followed by uppercase.

Implementing this pre-built pipe was easy. We did not even have to import anything.

There is no pipe in Angular to capitalize words, so we next will write a custom one.

To easily set up the template for a new custom pipe, using Angular CLI type:

ng generate pipe capitalize

This command created a file named capitalize.pipe.ts for us. Additionally, it added the import statement and declaration inside your app.module.ts file.

Alternatively, you could have created the file manually and added the declaration yourself, but the Angular CLI makes it easy by creating the template for everything we need.

Next, open up the capitalize.pipe.ts file, and modify the transform method to be the same as the one below:

Transform is where you insert the logic for how to output the data.

This file contains the @Pipe decorator, which we set the key value ‘name’ to ‘capitalize’. Later, we can use {{ data | capitalize }} in our html template.

The class implements PipeTransform which is an interface that contains the method transform.

<h1>
  Kittens
</h1>
<div *ngFor="let kitten of petStoreData.Kittens">
  <ul><label>Breed:</label> {{ kitten.breed | uppercase }}</ul>
  <ul><label>Name:</label> {{ kitten.name | capitalize }}</ul>
  <ul><label>Birthdate:</label> {{ kitten.birthdate }}</ul>
  <ul><label>Price:</label> {{ kitten.price }}</ul>
</div>

Once we have created the custom pipe, we can declare it in our template.

Again, we just use the pipe to transform the data, which now capitalizes their names.

It would be nice to have the kitten’s ages in months, rather than their date of birth. Again let’s generate another custom pipe through Angular CLI.

ng generate pipe ConvertToMonths

Here is a simple implementation of a pipe that converts a Date object to number of months. We implement our new pipe in our template again, this time changing the label “birthdate” to “age”.

<h1>
  Kittens
</h1>
<div *ngFor="let kitten of petStoreData.Kittens">
  <ul>Breed: {{ kitten.breed | uppercase }}</ul>
  <ul>Name: {{ kitten.name | capitalize }}</ul>
  <ul>Age: {{ kitten.birthdate | convertToMonths }}</ul>
  <ul>Price: {{ kitten.price }}</ul>
</div>
Now customers can do less math in their head.

Lastly, for the currency conversion functionality, we will chain two pipes together. We will utilize Angular’s built in CurrencyPipe which returns the currency symbol pre-pended to the value, and chain it to the converted foreign exchange value of the user’s selected currency.

ng generate pipe CustomCurrencyConvert

Here is a custom pipe that calculates exchanges rates (For simplicity, fx values were hard-coded).

We can also add a drop down list to dynamically select different currencies. Create data bindings to selected currency and make it able to be selected in a list. In our component, we declare some values:

Note: the implementation of the currency selector is not show but it is fairly simple. You will need to import FormsModule.

kitten.price gets chained by two pipes.

<h1>
  Kittens
</h1>
<div *ngFor="let kitten of petStoreData.Kittens">
  <ul>Breed: {{ kitten.breed | uppercase }}</ul>
  <ul>Name: {{ kitten.name | capitalize }}</ul>
  <ul>Age: {{ kitten.birthdate | convertToMonths }}</ul>
  <ul>Price: {{ kitten.price | customCurrencyConvert:selectedCurrency | currency:selectedCurrency:'true' }}</ul>
</div>

Note that we need to call our customCurrencyConvert pipe to change the value before we use CurrencyPipe as CurrencyPipe will convert the value to a string.

Here is our outputted values with Korean Won selected.

Overall, the company’s customers have a more attractive view of the data, plus the currency can be adjustable.

As well, we created separate pipe files that are separate and easily maintainable in the project.

In part II, we will discuss Angular’s AsyncPipe, as well as the pure and impure properties.