Pure vs Impure Pipes
In Angular, the distinction between Pure and Impure pipes is fundamental to how your application performs. By default, all pipes are "Pure," but knowing when to switch to "Impure" is key to handling complex data updates.
1. Pure Pipes (The Default)
A Pure Pipe is only called when Angular detects a "pure change" to the input value.
- For Primitives (String, Number, Boolean): It triggers when the value changes.
- For Objects/Arrays: It triggers only when the reference changes (e.g., assigning a new array). It will not trigger if you simply push a new item into an existing array.
Example: A Pure Filter Pipe
Behavior: If you useitems.push('Apple'), the UI will not update because the array reference remains the same. You would have to usethis.items = [...this.items, 'Apple']to trigger it.
2. Impure Pipes
An Impure Pipe is called during every change detection cycle, regardless of whether the input has changed. This includes mouse clicks, keystrokes, or timer events anywhere in the component.
Example: An Impure Filter Pipe
Behavior: If you use items.push('Apple'), the UI will update immediately because the pipe re-runs on every "tick."Comparison Table
| Feature | Pure Pipe | Impure Pipe |
| Execution | Only on input change (Value/Ref). | On every change detection cycle. |
| Performance | High (Optimized/Memoized). | Low (Can slow down the UI). |
| Instance | Shared across the template. | New instance for every usage. |
| Use Case | Formatting, simple transforms. | Async data, internal state, mutable data. |
When to use which?
- Use Pure Pipes for 99% of your needs (Date formatting, Currency, Uppercase). They are highly performant because Angular caches the results.
- Use Impure Pipes only when you must detect changes inside an object/array without changing its reference, or when your pipe has an internal state (like the built-in
AsyncPipe).
⚠️ Performance Warning
Be extremely careful with Impure Pipes in large lists (*ngFor). If you have 100 items and an impure pipe, and a user types in a text box, that pipe might execute 100 times for every single keystroke, potentially freezing your interface.