Can anyone please explain what is a pure and impure pipe in angular and how and where to use which one?
A pure pipe will only trigger change detection when one of its input values changes (e.g. you receive data from a backend endpoint (in a component) and the component’s view is updated thereby passing a new value to the pipe.
An impure pipe will run on every change detection cycle (click, scroll, etc). They are not great performance-wise but sometimes necessary.
I use an impure pipe to display error messaging since mutation of the error object on the form control class does not trigger change detection (the object reference stays the same even if the value of one of its keys changes).
Pure Pipe A pure pipe is only called when Angular detects a change in the value or the parameters passed to a pipe
@Pipe({ name: 'filterPipe', pure: true })export class FilterPipe {}
Impure Pipe An impure pipe is called for every change detection cycle no matter whether the value or parameter(s) changes. An impure pipe is called often, as often as every keystroke or mouse-move.
@Pipe({ name: 'filterPipe', pure: false})export class FilterPipe
In simple words, impure-pipe works for every change in the componentpure-pipe works only when the component is loaded.
impure-pipe
component
pure-pipe
(a, b) => a + b; is pure a => a + 2; is pure a => b => a + b; is pure a => a + b; is impure as it uses an external value (b) (a, b) => c = a + b; is also impure as it has a side effect (changes something outside its scope). Therefore, in a pure function or pure pipe, the function can only operate on its inputs and values scoped within the function/pipe. And it cannot change or replace values outside its scope. Therefore to be useful a pure function will always have at least one input and a return value. Examples of impure pipes in angular might be pipes that rely on services for data or create side effects. Generally, pipes should be pure, but there are some use-cases for impure pipes.