Pipes in Angular work a bit similarly to UNIX shell pipes. They take some data in an transform it into something else on the output.
Here’s a quick example:
name is a property defined within the conponent. The
uppercase token is
a pipe. It’s built in Angular and it turns the input into an uppercase
string. The source of the string (component’s property) does not get modified,
it’s just displayed uppercase in the browser.
There are a bunch of built-in pipes, and we can also create our own.
Some pipes support configuration via parameters. Here’s an example of how to use it:
DatePipe pipe accepts format parameter. In this case, we used the
The parameters may be dynamic, meaning we can use some variable as a value for the parameter.
The file name convention is to postfix it with
Here’s an example of a pipe that truncates inputs:
Any pipe needs to return string data.
This pipe accepts an optional parameter -
Non-standalone pipes should be registered in module’s declarations:
The custom pipe can be used just like any other pipe:
There is a built-in pipe that is useful for
displays the value only when it’s resolved. Until then, it will display an
empty string. It’s useufl for displaying the results of HTTP requests.
By default, pipes are pure. Angular
say that pipes use a simplified change detection mechanism. This matters when we
apply a pipe to some composite object. Pipes will not recalculate the output
when the content of composite objects changes (like changing a property of input
object, or changing the amount of items in an input array). This improves
performance. We can disable that optimization on our pipes with
added in the decorator of the pipe. With that, our pipe will be rerun whenever a composite object changes.
Note that the default change detection will work if we change the reference of the input composite object (e.g., pointing the variable to a different array).