Use Pipes in your next Angular Application! (Part 2)
Tags: angular, javascript
Published: 2020-04-01 03:20:50

Pipes are a pretty useful feature of Angular that allow us to transform the way we display data to our user without actually altering the data. Many times we may want to display dates, money, currency or just numbers in a preferred format. 

This article is a continuation of <u>[my first post about pipes here](https://dev.to/qarunqb/use-pipes-in-your-next-angular-application-part-1-39mk)</u> where we got familiar with the simpler pipes: 
 
 - Case-based pipes
   - UpperCasePipe
   - LoweCasePipe
   - TitleCasePipe
 - Number-based pipes
   - DecimalPipe
   - PercentPipe
   - CurrencyPipe

We'll be looking at 3 more pipes in this article, namely:

 - [JsonPipe](https://angular.io/api/common/JsonPipe)
 - [SlicePipe](https://angular.io/api/common/SlicePipe)
 - [KeyValuePipe](https://angular.io/api/common/KeyValuePipe)

_TL;DR: <u>[Here's the sample project with all the code](https://stackblitz.com/edit/ng-pipes-demo)</u>_

### [JsonPipe](https://angular.io/api/common/JsonPipe)

This pipe gives us a simple way to display complex data straight to our template. While we're not accustomed to showing raw JSON data for our users to see, Angular mentions in their documentation that this pipe is useful for debugging. I've personally found it immensely useful for displaying the value of a Reactive Form while changing the values. 

Let's look at a general example:

{% gist https://gist.github.com/Qarun-Qadir-Bissoondial/a77f2c952b395dfc24662aa21c061ff7 %}

And the corresponding output:

```
Object: [object Object]

Object with JsonPipe: { "name": "Qarun", "age": 25, "food": "Cheesecake", "languages": [ { "name": "JavaScript", "proficiency": "Wizard" }, { "name": "Python", "proficiency": "Avergae" }, { "name": "Elixir", "proficiency": "Beginner" } ] }

array: 1,2,3,4,5,6

array: [ 1, 2, 3, 4, 5, 6 ]
```

Displaying the object from the component directly into the HTML causes the raw string version to be shown. This is achieved by JavaScript automatically running `data.toString()`, hence the `[object Object]` in the examples without the pipe.

However, with the JsonPipe, it runs the variable through `JSON.stringify`, which is why our object shows properly and why the array with the pipe has brackets.

### [SlicePipe](https://angular.io/api/common/SlicePipe)

You're probably familiar with the [Array slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) and the [String slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice) methods in Vanilla JavaScript. They both slice out and return a specified portion of the Array/String.

Angular offers us a SlicePipe which works the same way, allowing us to manipulate with strings and arrays directly in our HTML template. It even allows us to change an array that `*ngFor` is applied to.

{% gist https://gist.github.com/Qarun-Qadir-Bissoondial/14b3ef9df8e75309b4c4c267d25ad9b1 %}

The above example shows one of the many use cases for the SlicePipe: hiding a long string. A button or "Read more" text can be clicked to show the full string. It's also useful if you want to build your own pagination when applied to `*ngFor`.
_Notice how in the very last array example, we included the JsonPipe at the end. **Pipes can be chained together**_.


### [KeyValuePipe](https://angular.io/api/common/KeyValuePipe)

Another useful Pipe is the KeyValuePipe which allows is to display objects. This is similar to the JsonPipe but with a slight twist. _It automatically sorts the object by keys._

Usually, the process of displaying an object's sorted contents goes something like this:
 - Get the object from some source in your TypeScript
 - Use Object.keys, Object.values, or Object.entries
 - Sort resulting array into a new array
 - Loop through new, sorted array and display values

KeyValuePipe cuts down that process by 50%. All you need is your comparator function and Angular does the rest. By allowing us to supply the comparator function, we still have the power to sort complex data structures. If no function is provided, then [defaultComparator](https://github.com/angular/angular/blob/master/packages/common/src/pipes/keyvalue_pipe.ts) is used.

{% gist https://gist.github.com/Qarun-Qadir-Bissoondial/28ac17d0fd32fc40b46a951cf56eae9d %}

And the corresponding output: 

```
Key-Value Pipes!

Default Key-Value pipe
age - 25
food - Cheesecake
name - Qarun

Custom Sort functions:

Sort by decreasing length of string values
food - Cheesecake
name - Qarun
age - 25

Sort by increasing expiry dates
Cabbage expires at Apr 14, 2020
Tomatoes expires at Apr 17, 2020
Lettuce expires at Apr 21, 2020
```

In the code above, I displayed 3 examples: 
 - Default KeyValuePipe
 - Sorting by decreasing length of strings
 - Sorting by increasing Expiry Date

The power of this pipe is only limited by your comparator function. Also, If you're wondering how my dates are displayed in such a readable format, that's because of the [DatePipe](https://angular.io/api/common/DatePipe) which I'll be covering as part of my next Article :) 

### Conclusion

You've made it to the end! In this article, we covered: 

 - JsonPipe
 - SlicePipe
 - KeyValuePipe

Thanks a lot for reading! Look out for my next article on some more exciting pipes :D