user11899717
user11899717

Reputation:

Angular Impure Pipe - should not be used , but any good scenario where using it is best

Angular Impure pipes should not be used , but if we use it then there could be a performance hit since they are executed for any component change detection cycle .

Could any tell me any scenario where using impure pipe is the only solution or using it is best ?

Upvotes: 2

Views: 444

Answers (3)

MindingData
MindingData

Reputation: 12508

If we take a look at Angular's own internal pipes that are impure, they are :

  • JsonPipe
  • SlicePipe
  • KeyValuePipe

All of these are impure because they take some sort of object type as the input param, so the typical change detection from pure pipes doesn't kick off the pipe. Makes sense.

But on top of that, atleast two of these are used for debugging purposes mainly (JSONPipe, KeyValuePipe), and slice... well.. I'm not that fond of it but it's atleast a lightweight pipe.

The key ingredients when doing an impure pipe IMO are

  • Super lightweight function. e.g. No async calls. No HTTP calls. Very little heavy lifting (Hell, one liner if you can).
  • Not used multiple times on one page (So.. If you have to use it, it's not used everywhere)
  • Has no sideeffects to other pipes. So the pipe should really just return data but not be used anywhere else (e.g. Do not pass that data somewhere else which goes somewhere else etc).

Documentation :

Upvotes: 0

user3740359
user3740359

Reputation: 405

When the output if the pipe is dependent on external values besides the input arguments of the pipe.

E.g. when you have a pipe that pretty prints a date:

  • '2019-11-13' should be displayed as 'Today'
  • '2019-11-12' should be displayed as 'Yesterday'
  • '2019-11-11' should be displayed as is.

... etc.

The pipe depends on the current date. So if it is 23:59 and 2 more minutes pass so it is 00:01 of the next day, the pipe needs to be updated. The same input parameter yields other output

Upvotes: 2

Youssef Tounoussi
Youssef Tounoussi

Reputation: 464

An impure pipe kind of pipes that trigger changes in the value or parameters, the best example for using it is the Google Translator for example, it triggers the user input and translates to the specified destination language

Upvotes: 0

Related Questions