An impure pipe is an Angular pipe whose result may change without a new input value or argument. Set `pure: false` in its `@Pipe` decorator to tell Angular to call `transform` during change detection even when the input and arguments appear unchanged. A pure pipe—the default—runs when its input value or an argument changes. section 17.3.4
Filtering a changing product array
A category filter receives a product array and returns products whose category matches the selected value. As a pure pipe, it can miss additions, edits, or deletions within that array: the array is still the same input object. Changing only the decorator to `pure: false` lets the filter reflect those changes without changing its `transform` logic. section 17.3.4
Listing 17.13. An impure pipe in the categoryFilter.pipe.ts file in the src/app folder
import { Pipe } from "@angular/core";
import { Product } from "./product.model";
@Pipe({
name: "filter",
pure: false
})
export class PaCategoryFilterPipe {
transform(products: Product[] | undefined,
category: string | undefined): Product[] {
if (products == undefined) {
return [];
}
return category == undefined ?
products : products.filter(p => p.category == category);
}
}
The complete filter shows the small decorator change and a `transform` method that returns an empty array for missing products or filters by category. section 17.3.4
Use this behavior selectively. Angular may call an impure pipe after any application data change or user interaction, even when the change is unrelated to its input. Keep `transform` simple; expensive work such as sorting an array can seriously harm performance. section 17.3.4
Other reasons a result can change while the input reference stays the same include:
- `slice` reflects changes inside an array, but repeats its slicing operation after unrelated application changes. section 17.4.7
- `async` displays the latest value received from an Observable; its updates originate outside the view, and its `transform` method may run even without a new event. section 17.4.11
- A custom discount pipe can inject a service and recalculate a price when the service’s discount changes, rather than relying only on a change to the price input. section 18.2.3
