How to use Angular 2 built-in Pipes in your TypeScript? Simple Trick.

Built-in Angular 2 pipes can easily be used in templates using interpolation. How to easily use the same pipes in your typescript components.

October 11, 2017 - 3 minute read -
angularjs angular2 the-how-series

Angular 2 built-in Pipes

There are tons of examples online on how to use pipes in your templates. They are pretty much used the same way as you used filters in Angular 1.x.

For example, if you want to format a value as currency it can be done as follows:

<p>A: {{a | currency:'USD':true:'1.0-0'}}</p>

So, if the value of a is 2345. It will be displayed as “$2,345”. That simple.

But, in my recent project, I had come across a situation where I wanted to use built-in pipes in my component file instead of the view. And pass that formatted value to the nested component.

Everywhere I searched I could find solutions to create custom pipes. And in such a custom pipe you can include built-in pipes and extend it as per your need. It was a little over-kill for the job I wanted to accomplish.

So, I gathered all the information I could and found a better, easier way to use built-in pipes directly on your data in your components.

Let’s see how this is done. Please follow a full working demo here.

The first thing to do is add CurrencyPipe as to the provider’s array in your module.

providers: [CurrencyPipe]

If your module is defined in some other file than your component, you will have to import CurrencyPipe in that file.

import {CurrencyPipe} from '@angular/common'

Then, import CurrencyPipe in your component.

import {CurrencyPipe} from '@angular/common'

Then create a private object representing the CurrencyPipe service.

constructor(private cp: CurrencyPipe) { ... }

Now, to use the currency formatting use just have to use the transform method provided by the pipe. Like below.

this.value = 12345;
this.value = this.cp.transform(this.value, 'USD': true: '1.0-0'); // $12,345

The first parameter is the value to be formatted. And the rest of the parameters are the usual pipe parameters you would pass depending on the type of pipe you are using. For more details check out the [Currency Pipe] documentation(https://angular.io/docs/ts/latest/api/common/index/CurrencyPipe-pipe.html).

In this case, 'USD' is the currency code. The 'true' value represents whether you want to use the symbol or not.

The '1.0-0' value represents a decimal pipe argument.

They are in a form of:

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

Again, you can find the full demo here.

Summary:

I hope this short and simple post comes handy when you come across any similar situation. Now, that you have learned how to use built-in pipes in your components, extending them to create your custom pipes is as much easy. Shoot me with any questions or concerns you have.

Never miss a post