DEV Community

Bearded JavaScripter
Bearded JavaScripter

Posted on • Edited on

1

Use Pipes in your next Angular Application! (Part 3)

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).

import { Component } from '@angular/core';
@Component({
selector: 'app-date-pipe',
template: `
<p>Date without Pipe: {{date}}</p>
<p>Date with Pipe: {{date | date}} </p>
<h3>Showing Dates</h3>
<p>Short Date: {{date | date:'shortDate'}}</p>
<p>Medium Date: {{date | date:'mediumDate'}}</p>
<p>Long Date: {{date | date:'longDate'}}</p>
<h3>Dates with Parameters</h3>
<p>dd/mm/yyyy: {{date | date:'d MMM y'}}</p>
<p>yyyy/mm/dd: {{date | date:'y MMM d'}}</p>
<h3>Formatting Times</h3>
<p>Short time: {{date | date:'shortTime'}}</p>
<p>Medium time: {{date | date:'mediumTime'}}</p>
<p>Long time: {{date | date:'longTime'}}</p>
`,
styleUrls: []
})
export class DatePipeComponent {
date: Date = new Date();
}

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
Enter fullscreen mode Exit fullscreen mode

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.

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-async-without-pipe',
template: `
<p *ngIf = 'dataLoaded; else loading'>{{character | json}}</p>
<ng-template #loading>
<p>Getting data from SWAPI...</p>
</ng-template>
`,
styleUrls: []
})
export class AsyncWithoutPipeComponent {
character: object;
dataLoaded: boolean = false;
constructor(private http: HttpClient) {
this.http.get(`https://swapi.co/api/people/1`).subscribe(char => {
this.character = char;
this.dataLoaded = true;
})
}
}

With the AsyncPipe, it can dramatically reduce the above code to the following:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Component({
selector: 'app-async-with-pipe',
template: `
<p *ngIf = 'character | async as char; else loading'>
{{char | json}}
</p>
<ng-template #loading>
<p>Loading using pipe...</p>
</ng-template>
`,
styleUrls: []
})
export class AsyncWithPipeComponent {
character: Observable<any>;
constructor(private http: HttpClient) {
this.character = this.http.get('https://swapi.co/api/people/1');
}
}

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 😄

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay