Pure pipes in Angular run only when the input reference changes. If the input object is the same (no new reference), Angular reuses the previous output to optimize performance.
Impure pipes run every time Angular runs change detection, even if the input reference or value has not changed. This can impact performance if used carelessly.
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'joinArray', pure: true }) export class JoinArrayPipe implements PipeTransform { transform(value: string[]): string { console.log('Pipe transform called'); return value.join(', '); } } // In component template: // {{ myArray | joinArray }} // In component class: // myArray = ['apple', 'banana']; // After some event: // myArray.push('cherry');
Pure pipes only run when the input reference changes. Mutating the array without changing its reference does not trigger the pipe to run again, so the output stays the same.
To declare an impure pipe in Angular, set the pure property to false in the @Pipe decorator. The default is pure: true.
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'lengthPipe', pure: false }) export class LengthPipe implements PipeTransform { transform(value: any[]): number { return value.length; } } // In component template: // {{ myArray | lengthPipe }} // In component class: // myArray = ['a', 'b']; // someMethod() { // this.myArray.push('c'); // }
Impure pipes run every time Angular runs change detection. If the component does not trigger change detection after mutating the array, the pipe will not update the output.