Pure pipe and impure pipe with examples

 In Angular, pipes are used to transform data in templates. There are two types of pipes in Angular: pure pipes and impure pipes. These pipes are used to modify or format data before it is displayed to the user, but they differ in how they behave when the input data changes.

Pure Pipes

A pure pipe is a pipe that only executes when the input to the pipe changes. Angular executes pure pipes only when the input data or parameters passed to the pipe change. Pure pipes are more efficient because they don't execute unnecessarily when data hasn't changed.

  • Pure Pipe Characteristics:
    • It runs only when the input data changes (i.e., when the reference of the input changes).
    • It is more efficient because Angular checks it less often.
    • By default, Angular pipes are pure unless explicitly marked as impure.

Impure Pipes

An impure pipe runs every time change detection is triggered, regardless of whether the input data changes or not. This means impure pipes are executed on every component or view update, making them less efficient.

  • Impure Pipe Characteristics:
    • It runs every time change detection is triggered.
    • It doesn't check whether the input data has changed or not.
    • Impure pipes are typically used for cases where the input data might be changing frequently or if it is non-primitive data (like arrays or objects) where changes can happen to the object or its properties without the reference changing.

To make a pipe impure, you need to set the pure property of the pipe's decorator to false.


Example of Pure Pipe

Let's create a simple pure pipe that formats a date into a readable format. By default, Angular pipes are pure, so this will be a pure pipe.

PurePipe Example:

  1. Pure Pipe Implementation:
typescript
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'pureDateFormat' }) export class PureDateFormatPipe implements PipeTransform { transform(value: any): string { if (!value) return ''; const date = new Date(value); return date.toLocaleDateString(); // Formats the date as "MM/DD/YYYY" } }
  1. Usage in Component:
typescript
@Component({ selector: 'app-date-display', template: ` <div> Original Date: {{ currentDate }} <br> Formatted Date: {{ currentDate | pureDateFormat }} </div> ` }) export class DateDisplayComponent { currentDate = '2024-11-28T14:00:00'; }
  1. Explanation:
    • The PureDateFormatPipe only triggers a transformation when the currentDate reference changes. It will not re-execute if the currentDate remains the same, even if the component re-renders due to other changes in the application.

Example of Impure Pipe

Now, let's create an impure pipe that filters an array. The pipe will run whenever change detection is triggered, regardless of whether the array reference changes.

Impure Pipe Example:

  1. Impure Pipe Implementation:
typescript
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'impureFilter', pure: false // This makes the pipe impure }) export class ImpureFilterPipe implements PipeTransform { transform(value: any[], searchTerm: string): any[] { if (!value || !searchTerm) return value; return value.filter(item => item.toLowerCase().includes(searchTerm.toLowerCase())); } }
  1. Usage in Component:
typescript
@Component({ selector: 'app-item-list', template: ` <div> <input [(ngModel)]="searchTerm" placeholder="Search items"/> <ul> <li *ngFor="let item of items | impureFilter: searchTerm"> {{ item }} </li> </ul> </div> ` }) export class ItemListComponent { items = ['Apple', 'Banana', 'Orange', 'Pineapple']; searchTerm = ''; }
  1. Explanation:
    • The ImpureFilterPipe is marked as pure: false, which means that Angular will re-execute this pipe every time change detection is triggered, even if the input array (items) doesn't change.
    • For example, if the user types something in the search box, the pipe will execute to filter the list. However, if the items array is modified in some other way (e.g., adding/removing items), the pipe will still execute even if the reference to items does not change.

When to Use Pure vs Impure Pipes

  • Pure Pipes:

    • Use cases: When your pipe performs operations that do not need to be executed unless the input data or reference changes. For example, formatting data, transforming input to a specific format, or applying simple logic.
    • Efficiency: Pure pipes are more efficient because they only execute when necessary, reducing the number of computations.
  • Impure Pipes:

    • Use cases: When the input data is frequently changing, or if you need to handle non-primitive values (such as objects or arrays), and you want the pipe to execute every time the view is re-rendered.
    • Efficiency: Impure pipes are less efficient because they run on every change detection cycle, even when the input data hasn’t changed.

Summary of Differences

FeaturePure PipeImpure Pipe
ExecutionExecutes only when input data changes (reference change).Executes every time change detection is triggered.
EfficiencyMore efficient.Less efficient due to frequent execution.
Use CasesFor static or simple data transformations.For dynamic data or complex transformations like arrays, lists, etc.
DefaultBy default, pipes in Angular are pure.Needs to be explicitly set as pure: false in the pipe decorator.

In conclusion, pure pipes are great for optimizing performance and are used in most scenarios, while impure pipes are necessary when dealing with data that changes frequently or when you need to re-evaluate the transformation on every change detection cycle.

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

Building strong foundational knowledge in frontend development topics