Course Content
Introduction to Angular
Introduction to Angular
Creating a Custom Pipe in Angular
Sometimes, the built-in pipes in Angular just aren't enough. You might need a unique transformation that's specific to your app. In that case, you can create your own custom pipe.
Let's say you have a list of tasks, and each task can be either completed or not. To make completed tasks visually stand out, you want to automatically add a β emoji to their titles. Instead of hardcoding this logic into every template, you can build a dedicated pipe for it.
How to Create a Custom Pipe
To generate a custom pipe in Angular, use the following CLI command. We'll call it formatTitle
, since its job is to format the task title based on its completion status:
This will create two files:
format-title.pipe.ts
β the pipe logic;format-title.pipe.spec.ts
β a unit test file (you can delete it if you don't need testing right now).
When Angular generates the pipe, it looks something like this:
pipe
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'formatTitle', standalone: true }) export class FormatTitlePipe implements PipeTransform { transform(value: unknown, ...args: unknown[]): unknown { return value; } }
Here's what this code does:
The
FormatTitlePipe
class implementsPipeTransform
, which ensures the pipe has atransform
method;The
transform
method receives a value (the input) and optional arguments and returns a transformed result. At this point, it just returns the input as-is;The pipe's name (
formatTitle
) is defined in the@Pipe
decorator β that's the name you'll use in the template.
Right now, the pipe exists but doesn't actually do anything. Let's add the actual logic next.
Custom Pipe Implementation
We need to add an β
emoji to the title based on the task's completion status (task.completed
). Update the pipe to apply our custom formatting logic:
pipe
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'formatTitle', standalone: true }) export class FormatTitlePipe implements PipeTransform { transform(value: string, completed: boolean): string { return completed ? value + " β " : value; } }
The transform
method takes two arguments:
value
β the task title;completed
β a boolean indicating whether the task is done.
If the task is complete (true
), it adds a β
emoji at the end of the title. Otherwise, it just returns the title unchanged.
Using the Pipe in a Template
To use the pipe in your Angular template, apply it with the pipe symbol |
:
template
<div class="task-title">{{ task.title | formatTitle:task.completed }}</div>
What's happening here:
task.title
is the value passed to the pipe;formatTitle:task.completed
applies the pipe and sends in thecompleted
flag;The title will either include the β emoji or not, depending on the task's status.
Using pipes like this helps keep your templates clean and readable, and pushes the formatting logic into reusable, testable code.
Thanks for your feedback!