How to create custom pipes?

Earlier this month, we covered how to create custom directives. Today, let’s tackle how to create custom pipes. Pipes help format data such as strings, dates, numbers, etc. The first thing to do is to use the Angular CLI:

ng generate pipe [name]

or ng g p [name]

It’s also possible to generate standalone pipes with the --standalone option:

ng generate pipe [name] --standalone

This creates a class with a single method transform to implement:

By default, the types are all set to unknown, as Angular CLI cannot guess what kind of data we want to format. As we know what we want to format and how, as well as how many arguments our pipe can accept, we can change that signature to make it more meaningful as follows:

Most pipes have optional parameters, so it’s always a good idea to have a default value for each, as I did in this example with displayPrefix = true.

Such a pipe can safely be used as follows:

Or, if we want to turn off the prefixes, we can use our optional parameter and set its value to false:

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.