Understanding Pipes in Angular
Hi everyone. In this article, I am going to explain pipes in Angular. There are two types of pipes in Angular: Built-in pipes and custom pipes.
- What is the pipe?
- When we should create a custom pipe?
Pipes are basically helping us to transform data. For example, if you want to display all the text in lower case. You can make it quickly by using built-in pipes. {{ your_variable | LowerCasePipe}}
Angular has two types of pipe.
- Built-in Pipes (for more info https://angular.io/guide/pipes)
- Custom Pipes
So when do we need to create a custom pipe?
If you need to transform the array(Maybe you will sort items by the newest date) or there is no built-in pipe you need. You can make it your own pipe.
Let’s start with built-in Pipes
- Upper Case Pipe
- Lower Case Pipe
- Async Pipe
- Currency Pipe
- Date Pipe
- Slice Pipe
- Json Pipe
- Percent Pipe
and So on.
Upper case Pipe
This pipe is used when you need to display all text upper case.
Lower case Pipe
This pipe is used when you need to display all text lower case.
Async pipe
Async pipe basically subscribes to your observable item to get data. Maybe you can say that why don't we subscribe in our typescript file because it causes memory leak to avoid that it is the best use “async pipe”.
https://medium.com/@sub.metu/angular-how-to-avoid-memory-leaks-from-subscriptions-8fa925003aa9
Currency Pipe
Every country has its currency and its symbol. Each country handles numbers or symbols differently. So are you going to code for each country? Here comes to help currency pipe.
Date Pipe
It’s common to use timestamps when you store the data in the database. So when the data comes you need to do some calculations and you don’t want to display all dates “Date pipe” is pretty useful.
Slice Pipe
There is an array or maybe a string and if you don’t want to display all the data slice pipe will be a good choice.
Json Pipe
Json pipe used when displaying object data type to json format.
Percent Pipe
It calculates the percent of data.
Now let’s create our pipe. I assume that you already have a project.
Let's create our pipe using ng generate pipe SortByDate
Ng generates gives us a class implement from PipeTransform
the interface. Then we should define transform()
the method. This method takes two arguments. The first one is the value which refers to the text. Another argument is to add some conditions to it. For example, you are trying to slice
the text. So how many characters do you want to take? In this scenario, you can use other arguments. You can check the link for example.
Let’s turn our pipe…
Thank you for reading :)