Fundamentals
Pipes
Master Angular Pipes, covering built-in formatting options (date, currency, async), pure vs impure change detection, and custom pipes implementations.
1. Learning Objectives
In this lesson, you will master Angular pipes. By the end of this topic, you will be able to:
- Explain the purpose of pipes for formatting data in template views.
- Use built-in pipes (
date,uppercase,currency,json). - Chain multiple pipes together inside a template expression.
- Differentiate between pure and impure change detection options in pipes.
- Create custom pipes by implementing the
PipeTransforminterface.
2. Overview
Pipes are simple functions designed to format and transform output data directly inside template expressions. They take input values, transform them based on arguments, and return the formatted output to the view, without modifying the underlying component state variables.
3. Why This Topic Matters
Using pipes correctly improves rendering performance and simplifies formatting:
- Slow Lists from Component Function Calls: Calling component class methods directly inside a template interpolation (e.g.
{{ formatName(user) }}) triggers on every change detection cycle, slowing down rendering. Using a pure pipe cached the results, updating only when input parameters change. - Uncleaned Subscriptions from Observables: Handling asynchronous streams manually can lead to memory leaks if subscriptions are not cleared. Using the built-in
asyncpipe automatically subscribes and unsubscribes when components are destroyed.
4. Real-World Analogy
Think of an Angular pipe like **a water filter faucet attachment**:
- The Water Source (Raw Data): The main water pipe carries raw, unfiltered water (e.g. a timestamp number like
1710526000). - The Filter Attachment (The Pipe): The faucet has a filter attachment (e.g.
| date:'short'). The raw water passes through the filter, changing its format as it flows. - The Glass of Water (Formatted Output): You get clean, refreshing water in your glass (e.g.
"3/15/26, 2:00 PM"). The water source in the main pipe remains unchanged.
5. Core Concepts
Angular pipes support several key features:
- Built-in Pipes: Angular includes standard pipes for common formatting needs:
currency,date,decimal,json, andasync. - Pure Pipes (Default): Pure pipes are optimized for performance. They only re-run when their input reference changes (e.g. a string changes or an array reference updates).
- Impure Pipes: Impure pipes (declared with
pure: false) run on every change detection cycle, regardless of whether inputs changed. Use them only when tracking internal mutations of objects or arrays.
| Pipe Type | Change Detection Behavior | Ideal Use Case |
|---|---|---|
| Pure Pipe (Default) | Runs only when inputs change by value or reference. | Formatting text, currency conversions, date conversions (high performance). |
| Impure Pipe | Runs on every change detection cycle (e.g. keyboard clicks, mouse moves). | Filtering arrays when elements inside the array mutate (can cause lag). |
6. Syntax & API Reference
Below is a custom pipe that truncates text and appends an ellipsis:
7. Visual Diagram
This diagram displays how data flows through a pipe:
8. Live Example — Full Working Code
Below is a standalone component that showcases built-in pipes, pipe chaining, and a custom truncate pipe:
9. Interactive Playground
Try It Yourself Challenges:
- Change parameters in the
truncatepipe (e.g. limit to 10 characters) and notice how the template updates. - Test what happens when you pass an invalid date object into the
datepipe. (Angular will print a template console warning).
10. Common Mistakes
| Mistake | Why it happens | Wrong | Correct |
|---|---|---|---|
| Method calls in templates for formatting | Calling component class methods inside template interpolation to format text, causing the function to run on every change detection cycle. | <p>{{ getFormattedText(item) }}</p> |
<p>{{ item | formatText }}</p> (Using pure pipes) |
11. Best Practices
- Keep pipes pure for performance: Keep custom pipes pure by default. Avoid setting
pure: falseunless you specifically need to track internal mutations of objects or arrays. - Use the async pipe for asynchronous streams: Use the built-in
asyncpipe to bind Observables directly in templates. This ensures subscriptions are automatically cleaned up when the component is destroyed. - Chain pipes logically: Pay attention to execution order when chaining pipes. For example, formatting a date to a string first prevents you from chaining date-specific configuration options later:
{{ dateValue | date:'short' | uppercase }}works, but{{ dateValue | uppercase | date:'short' }}will fail.
12. Browser Compatibility/Requirements
Built-in pipes use standard JavaScript Internationalization (Intl) APIs to format dates and currency values. Ensure modern browser environments are available.
13. Interview Questions
🟢 Q1: What is the difference between a pure and an impure pipe?
Answer:
- A pure pipe (default) is called only when Angular detects a change to the input value or reference. If the input remains unchanged, Angular reuses the cached output.
- An impure pipe is called on every change detection cycle (e.g. keystroke or click), even if inputs have not changed. Impure pipes can slow down performance and should only be used when necessary (such as tracking internal array changes).
14. Debugging Exercise
Identify and fix the compiler error in this custom pipe:
Diagnosis: The pipe class implements the PipeTransform interface but does not define the required transform() method. TypeScript will throw a compilation error. To fix this, implement the transform() method with at least one parameter matching the input value.
Fixed custom pipe:
15. Practice Exercises
Exercise 1: Create a Celsius to Fahrenheit converter pipe
Build a standalone custom pipe named `temperature` that takes a number (Celsius value) and converts it to Fahrenheit. Use it in a component template.
16. Scenario-Based Challenge
The API Date Formatter Challenge:
An API returns task items containing date strings in ISO format (e.g. "2026-07-15T08:00:00Z"). The product manager wants dates displayed in the format "July 15, 2026". Write a template implementation using built-in date pipes to format these values.
17. Quick Quiz
Q1: Which built-in pipe is used to subscribe to Observables directly inside templates?
A) observable
B) subscribe
C) async
Answer: C — The built-in async pipe handles subscriptions and cleanups for Observables automatically inside templates.
18. Summary & Key Takeaways
- • Pipes transform input values into formatted string outputs for template views.
- • Pure pipes cache results, re-running only when input values or references change.
- • Use the async pipe to bind asynchronous streams and handle subscriptions automatically.
19. Cheat Sheet
| Interface | Required Method |
|---|---|
PipeTransform |
transform(value: any, ...args: any[]): any |