When Angular's built-in pipes don't cover a formatting need specific to your app, you can build your own. This lesson walks through creating, parameterizing, and testing a custom pipe.
What Is a Custom Pipe?
A custom pipe is a class decorated with @Pipe that implements the PipeTransform interface's transform() method, taking an input value (and optional arguments) and returning the transformed output for display.
Custom pipes are ideal for formatting logic specific to your domain, truncating long text with an ellipsis, converting a status code into a human-readable label, or formatting a custom unit of measurement.
Because pipes are plain classes with a single transform() method, they are simple to unit test without any Angular testing utilities, just instantiate the class and call the method directly.
describe('TruncatePipe', () => {
it('truncates long strings and appends an ellipsis', () => {
const pipe = new TruncatePipe();
expect(pipe.transform('Hello there, world!', 8)).toBe('Hello th...');
});
});
Common Mistakes
Performing expensive computations (like API calls) inside transform(), which can run frequently.
Forgetting standalone: true (or module declaration) so the pipe can be imported where needed.
Not marking pipes pure: false when they genuinely need to react to internal, non-reference state changes.
Duplicating the same formatting logic across multiple components instead of extracting a shared custom pipe.
Key Takeaways
Custom pipes implement PipeTransform and its single transform() method.
The first transform() argument is the piped value; subsequent arguments come from the template after colons.
Custom pipes are easy to unit test since they're plain classes with no special Angular test setup required.
The Angular CLI's ng g pipe scaffolds a correctly structured pipe and spec file.
Pro Tip
Keep custom pipes pure and side-effect free. If a transformation needs live, streaming data (like a WebSocket feed), prefer combining it with the built-in async pipe rather than building a stateful impure pipe.
You now know how to build custom Angular pipes. Next, learn about the Component Lifecycle to understand how Angular creates, updates, and destroys components.