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
.
Assuming we change the name of the pipe in the decorator to personName
, 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
: