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.
In this article, we'll be moving on to 2 very useful pipes:
And the corresponding output:
Date without Pipe: Fri Apr 03 2020 08:43:22 GMT-0400 (Venezuela Time)
Date with Pipe: Apr 3, 2020
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
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.
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 is defined, then show the
<p> tag. Else, show the
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 :)
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 😄