Angular 8 Pipes | All Type of Pipes with Examples

In a real-world application, we may receive data in multiple forms, but some of these could in complex formats which are not easy for normal users to understand. For example Date object shows to date in a format like this

Sat Aug 03 2019 19:48:11 GMT+0530 (India Standard Time)

But it’s better to have something like this:

Saturday, 03 Aug 2019 07:50 PM

What are pipes in Angular?

Angular provides some helpful filters known as Pipes which makes it very easy to format or transform the data value according to our needs.

Pipes are used with a Pipe (|) character, it takes an input and returns a desired formatted output. Simple Right?

How to use a Pipe?

Pipes can be easily used in HTML templates. For example, convert big date object into readable formate.

Without Pipe

With date Pipe

Adding Parameters in Pipes

Any number of the optional parameter(s) can be added in pipes by adding a (:) character. Like in date pipe which we used above can be used as follows:

 

Type of Built-in Pipes in Angular

Angular provides a number of Pipes:

DatePipe, CurrencyPipe, AsyncPipe, DecimalPipe, JsonPipe, KeyValuePipe, LowerCasePipe, PercentPipe, SlicePipe, TitleCasePipe, UpperCasePipe

How to create a custom Pipe?

There is a number of Built-in Pipes available, sometimes we may want to transform values in custom formats. Let’s check how we can create our own Pipes in Angular application.

Create a new class which will import Pipe class and have @Pipe decorator with meta-information name

Run following ng command in CLI to generate a new pipe named ‘foo

Above command will add FooPipe in app.module.ts file’s declaration array.

The foo.pipe.ts file will look like this:

Change the transform method with following to return a modified value.

Now we can use this Pipe in the template:

Multiple Pipes by Chaining

Multiple Pipes can be used on single value with the chaining of Pipe character as follows:

 

Conclusions: In the above article, we discussed Pipes in Angular and how we can use built-in and create our own custom pipe classes using @Pipe decorator.

 

Thanks for visiting :) Let me know if you have some suggestions or feedback for this post in the comment section. Looking for any tutorial or demo on FreakyJolly, just drop me a message here

Leave a Reply

avatar
  Subscribe  
Notify of