3 Angular pipes you should know about

Alain Chautard
Angular Training
Published in
3 min readAug 14, 2018

--

Pipes can be used creatively for debugging purposes

With Angular 6.1 was released a new pipe: KeyValuePipe. In this article, I’m going to cover this new pipe as well as two others that can be used for multiple purposes.

Json Pipe

Let’s start with a very cool pipe that makes debugging a breeze: The JSON pipe.

You’re probably aware that displaying an object in an Angular expression does not help us much:

Displaying an object in an expression just renders [object Object]

But if we bring the JSON pipe into play, now we’re getting a nicely formatted and helpful output:

Using the JSON pipe, we can now see the actual data

Of course, the JSON pipe is mostly helpful for development / debugging purposes, unless your production application uses some JSON rendering, in which case the JSON pipe is exactly what you need.

Async Pipe

The async pipe is the most elegant way to subscribe to an observable in Angular code. On top of being a fantastic syntax shortcut, the async pipe will also automatically unpack your data and unsubscribe from the source observable when your component is removed from the DOM.

First here is what an example would look like without the async pipe:

That’s an awful lot of code to just subscribe to a data source and unsubscribe from it. We have to keep track of the Subscription and implement ngOnDestroy to properly unsubscribe.

Now let’s enjoy the difference that the async pipe makes here:

No more subscription nor unsubscription, we just get our Observable, apply the async pipe to it, and done!

Source code on Stackblitz:

Key Value Pipe

Let’s now see the new KeyValuePipe in action. It is a little bit similar to the json pipe in some ways, as it allows us to turn an object into something that developers can use in a different way.

Here we apply it on an object and then on a map, and what we get as a result is a way to access both keys and values:

Source code on Stackblitz:

Chain pipes to do even more

And if you’re not sure what the KeyValuePipe does, remember that pipes can be chained, so we can use the JSON pipe to see what happens there. Add a <pre> tag on top of that and you end up with this nice preformatted output:

I hope you enjoyed these tricks. Pipes are often under-estimated, yet they can bring a lot of value to your Angular applications when used properly.

My name is Alain Chautard. I am a Google Developer Expert in Angular, as well as founding consultant and trainer at Angular Training where I help web development teams learn and become fluent with Angular. Need help with Angular? Let’s schedule some time to talk.

If you enjoyed this article, please clap for it or share it. Your help is always appreciated.

--

--