tezvyn:

Angular Custom Pipes: Transform Data in Your Templates

AI-drafted, machine-checkedSource: angular.devbeginner
Angular Custom Pipes: Transform Data in Your Templates

An Angular custom pipe is a reusable formatting function for your templates. Use it for common display transformations like currency or date formatting, keeping your component logic clean. Footgun: Avoid slow logic; pipes run often and can kill performance.

WHY IT EXISTS Custom pipes exist to separate presentation logic from component logic. Instead of repeatedly formatting data (like dates or currency) inside your component's TypeScript code, you can create a reusable transformer that you apply directly in the HTML template, making your components cleaner and your templates more declarative.

THE MENTAL MODEL A custom pipe is a function you can use in your HTML. It takes data as input, transforms it, and outputs the formatted result for display. Think of it as a filter in a pipeline (|) that your data flows through before it's rendered on the screen. It's meant for pure, stateless transformations.

HOW IT WORKS To create a custom pipe, you define a class with the @Pipe decorator. This class must implement the PipeTransform interface, which requires a single method: transform(). The transform method takes the value to be transformed as its first argument, followed by any optional parameters. In the template, you use the pipe's declared name with the pipe character: {{ data | myPipe:arg1:arg2 }}.

WHEN TO USE IT Use custom pipes for simple, stateless, and fast data formatting that you need to reuse across your application. Good use cases include: formatting a number as a phone number, truncating a long string with an ellipsis, capitalizing text, or sorting a small, static list for display.

WHEN NOT TO USE IT Avoid using pipes for any computationally expensive or asynchronous operations. Because pipes can be executed on every change detection cycle (which can be frequent), a slow pipe will severely degrade your application's performance. Do not use pipes to filter large arrays or make HTTP requests; handle that logic within your component or a service instead.

ONE CANONICAL EXAMPLE Let's create a pipe to convert a file size in bytes to a more readable format (KB, MB). You would create a class decorated with @Pipe({ name: 'fileSize' }). Its transform method would take a number (bytes) and an optional decimal precision. The logic would divide the bytes by 1024 until it reaches the appropriate unit, then return a formatted string like "15.2 MB". You would use it in a template like this: Attachment size: {{ 15923283 | fileSize:1 }}.

Read the original → angular.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.