What is a difference between pure and impure pipe?

In Angular, pipes can be classified as either pure or impure. The distinction between pure and impure pipes determines how often the pipe’s transform method is called by Angular.

A pure pipe is only re-evaluated (and its transform method is called) when one of its arguments changes. For example, a pure pipe that formats a date would only be re-evaluated and its transform method called if the date changes. Pure pipes are optimized for performance, as they are only called when necessary.

An impure pipe, on the other hand, is re-evaluated and its transform method called for every change detection cycle, regardless of whether or not the arguments have changed. Impure pipes are useful when you need to perform a calculation that can change with time, such as filtering a list based on user input.

By default, Angular pipes are pure. You can make a pipe impure by setting the pure property of the @Pipe decorator to false. Here is an example of an impure pipe:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter',
  pure: false
})
export class FilterPipe implements PipeTransform {
  transform(items: any[], searchText: string): any[] {
    if (!searchText) {
      return items;
    }
    return items.filter(item => item.name.toLowerCase().indexOf(searchText.toLowerCase()) !== -1);
  }
}

In this example, the FilterPipe is an impure pipe because the pure property of the @Pipe decorator is set to false. This means that the pipe’s transform method will be called for every change detection cycle, which is necessary for filtering a list in real-time based on user input.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *