Pipes help change data in templates. Pure and impure pipes decide when to update the displayed data.
Pure vs impure pipes in Angular
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'examplePipe', pure: true // or false }) export class ExamplePipe implements PipeTransform { transform(value: any, ...args: any[]): any { // transform logic here return value; } }
The pure property controls if the pipe is pure (true) or impure (false).
Pure pipes run only when input references change. Impure pipes run on every change detection cycle.
@Pipe({ name: 'purePipe', pure: true })
export class PurePipe implements PipeTransform {
transform(value: string): string {
return value.toUpperCase();
}
}@Pipe({ name: 'impurePipe', pure: false })
export class ImpurePipe implements PipeTransform {
transform(value: string): string {
return value + ' updated';
}
}This example shows two pipes: one pure and one impure. Clicking the button sets the text to the same string. The pure pipe runs only if the input reference changes, so it may not run. The impure pipe runs every time Angular checks for changes, so it always runs.
import { Component, Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'purePipe', pure: true }) export class PurePipe implements PipeTransform { transform(value: string): string { console.log('PurePipe transform called'); return value.toUpperCase(); } } @Pipe({ name: 'impurePipe', pure: false }) export class ImpurePipe implements PipeTransform { transform(value: string): string { console.log('ImpurePipe transform called'); return value + ' updated'; } } @Component({ selector: 'app-root', template: ` <h3>Pure Pipe Output: {{ text | purePipe }}</h3> <h3>Impure Pipe Output: {{ text | impurePipe }}</h3> <button (click)="changeText()">Change Text</button> ` }) export class AppComponent { text = 'hello'; changeText() { this.text = 'hello'; // same string value, new reference } }
Pure pipes improve performance by running less often.
Impure pipes can slow down your app if overused because they run very often.
Use impure pipes only when you need to detect changes inside objects or arrays without changing their reference.
Pure pipes run only when input references change.
Impure pipes run on every change detection cycle.
Choose pure pipes for better performance and impure pipes when you need frequent updates.