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:
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.
If your module is defined in some other file than your component, you will have to import
CurrencyPipe in that file.
CurrencyPipe in your component.
Then create a private object representing the
Now, to use the currency formatting use just have to use the
transform method provided by the pipe. Like below.
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.
'1.0-0' value represents a decimal pipe argument.
They are in a form of:
Again, you can find the full demo here.
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.