Final answer:
In Angular, a pure pipe is executed only when there is a change in its input values, making it efficient for performance. An impure pipe is executed on every change detection cycle, making it useful for dynamic operations but less performant. Examples include a date formatting pure pipe and a filter impure pipe.
Step-by-step explanation:
The difference between pure and impure pipes in Angular relates to how they handle change detection and execution. A pure pipe is only executed when Angular detects a change in the input value or the input values that affect the result. This means that pure pipes are very performant, as they do not recalculate every time a change detection cycle runs, but only when their inputs change.
For example, consider a pure pipe that converts a date to a human-readable format. It will only re-run its transformation if the input date changes, which means it won't execute if other unrelated components on the page change or an unrelated event occurs.
Example of a Pure Pipe:
import { Pipe, PipeTransform } from 'at the rate of angular/core';
at the rate of Pipe({
name: 'readableDate',
pure: true
})
export class ReadableDatePipe implements PipeTransform {
transform(value: Date): string {
return value.toDateString();
}
}
An impure pipe, on the other hand, is checked for every change detection cycle, regardless of whether the input has changed. This can be useful for pipes that depend on external state or asynchronous operations, but it can also lead to performance issues since the pipe is executed more frequently.
An example of an impure pipe might be a filter pipe that depends on multiple components and global state. Even if the input list doesn't change, the output might change because the filter criteria stored externally changed.
Example of an Impure Pipe:
import { Pipe, PipeTransform } from 'at the rate of angular/core';
at the rate of Pipe({
name: 'filterPipe',
pure: false
})
export class FilterPipe implements PipeTransform {
transform(list: any[], filterText: string): any[] {
// Filter logic here
return filteredList;
}
}
It's important to choose the type of pipe based on the use case to balance between performance and responsiveness.