Learning Angular Pipes – Part II

Async Pipe. Pure vs Impure Pipes.

Kelvin Yan

PUBLISHED:

Async Pipes

Unlike in part I of Angular pipes, async does not format existing data. It only waits for data to be received.

In the below example, we have our data bound to an observable, and then wait 1 second for data to be received after we click the button.

Instead of our expected result, we get [object Object]. Note: this would occur whether or not we have delay.

We know that data is received after 1 second, but we still need to subscribe to that data. When we use async, it subscribes automatically.

Async pipe
After clicking, we now see the data as it appears after 1 second.

Advantages of using async include:

  1. Data can be an Observable rather than a Subscription.
  2. It unsubscribes automatically when the component is destroyed (no memory leaks).
  3. End up writing less code.

Pure vs Impure Pipes

By default, all pipes are pure. You can make them impure by creating a custom pipe and setting the property pure to false. Async is an example of an impure pipe. It is always checking for new input data.

Pure will be true if not specified.

The pure property tells Angular whether or not the value should be recomputed when its input changes.

When the pipe is pure, it does not check the input to see whether or not to update the transformed data.

Pure defaults to true for good reasons. Sometimes there is no need to keep recalculating on every change detection. On a large list of items, it could cause performance issues.

Angular defaults this behaviour to true and lets the developer decide whether or not impure is required.