The main use of Pipes in Angular is to transform how data is displayed. Dates, currency and JSON objects are just some of the structures that Angular Pipes can work with.
Check out my first and second articles on Pipes where we cover some of the simpler pipes.
In this article, we'll be moving on to 2 very useful pipes:
DatePipe
This is used for displaying JavaScript Date Objects in a readable format. Angular provides many ways for us to configure the DatePipe, from full or abbreviated day names, from the hours down to the seconds and, of course, varying locales as well (en-US locale is used by default).
And the corresponding output:
Date without Pipe: Fri Apr 03 2020 08:43:22 GMT-0400 (Venezuela Time)
Date with Pipe: Apr 3, 2020
Showing Dates:
Short Date: 4/3/20
Medium Date: Apr 3, 2020
Long Date: April 3, 2020
Date Formatting with Parameters:
dd/mm/yyyy: 3 Apr 2020
yyyy/mm/dd: 2020 Apr 3
Formatting Times
Short time: 8:43 AM
Medium time: 8:43:22 AM
Long time: 8:43:22 AM GMT-4
There's loads more examples on the DatePipe Documentation. Pre-defined formatting options as well as custom formats.
AsyncPipe
Asynchronous Programming is at the very heart of JavaScript. With Angular being built on RxJS and using Observables for HTTP requests, more and more developers end up writing the same code just to extract their data from HTTP Async responses.
With the AsyncPipe, it can dramatically reduce the above code to the following:
The HTML from the second example is important.
Line 8 says: "Subscribe to the character
observable and store the response data in char
. If char
is defined, then show the <p>
tag. Else, show the #loading
template."
This allows us to set a variable to store the response data straight from the HTML as opposed to declaring it in our Component TypeScript.
Additionally, notice how in the second example, we didn't need to call subscribe. This is because AsyncPipe automatically subscribes for you. Generally speaking, we don't need to unsubscribe from HTTP Observables since Angular auto-unsubscribes for us.
But in general, AsyncPipe automatically unsubscribes Observables on Component Destruction. That's a lot less for us for think about and a lot less for us to code. Always leverage the framework as much as possible.
Note that the same works for promises as well :)
Conclusion
This article was a short, but powerful, introduction to using DatePipe and AsyncPipe in Angular. DatePipe is used to display dates and can show various formats. AsyncPipe extracts the value from an asynchronous data structure and gives us access to it straight from the HTML.
Thanks a bunch for reading! Stay tuned for the next Article where I talk about making your own pipes 😄
Top comments (0)