Every application starts out with what seems like a simple task: get data, transform them, and show them to users. Getting data could be as simple as creating a local variable or as complex as streaming data over a Websocket.
Once data arrive, we could push their raw toString
values directly to the view.
That rarely makes for a good user experience.
E.g., almost everyone prefers a simple birthday date like
April 15, 1988 to the original raw string format
— Fri Apr 15 1988 00:00:00 GMT-0700 (Pacific Daylight Time).
Clearly some values benefit from a bit of massage. We soon discover that we desire many of the same transformations repeatedly, both within and across many applications. We almost think of them as styles. In fact, we'd like to apply them in our HTML templates as we do styles.
Introducing Angular pipes, a way to write display-value transformations that we can declare in our HTML!
Try the
Using Pipes
A pipe takes in data as input and transforms it to a desired output. We'll illustrate by transforming a component's birthday property into a human-friendly date.
lib/hero_birthday1_component.dart
Focus on the component's template.
Inside the interpolation expression we flow the component's birthday
value through the
pipe operator ( | ) to the Date pipe
function on the right. All pipes work this way.
The Date
and Currency
pipes need the ECMAScript Internationalization API.
Safari and other older browsers don't support it. We can add support with a polyfill.
Built-in pipes
Angular comes with a stock of pipes such as
DatePipe
, UpperCasePipe
, LowerCasePipe
, CurrencyPipe
, and PercentPipe
.
They are all immediately available for use in any template.
Learn more about these and many other built-in pipes in the API Reference; filter for entries that include the word "pipe".
Angular doesn't have a FilterPipe
or an OrderByPipe
for reasons explained in an appendix below.
Parameterizing a Pipe
A pipe may accept any number of optional parameters to fine-tune its output.
We add parameters to a pipe by following the pipe name with a colon ( : ) and then the parameter value
(e.g., currency:'EUR'
). If our pipe accepts multiple parameters, we separate the values with colons (e.g. slice:1:5
)
We'll modify our birthday template to give the date pipe a format parameter. After formatting the hero's April 15th birthday, it should render as 04/15/88:
The parameter value can be any valid template expression such as a string literal or a component property. In other words, we can control the format through a binding the same way we control the birthday value through a binding.
Let's write a second component that binds the pipe's format parameter
to the component's format
property. Here's the template for that component:
lib/hero_birthday2_component.dart (template)
We also added a button to the template and bound its click event to the component's toggleFormat()
method.
That method toggles the component's format
property between a short form
('shortDate'
) and a longer form ('fullDate'
).
lib/hero_birthday2_component.dart (class)
As we click the button, the displayed date alternates between "04/15/1988" and "Friday, April 15, 1988".
Learn more about the DatePipes
format options in the API Docs.
Chaining pipes
We can chain pipes together in potentially useful combinations.
In the following example, we chain the birthday to the DatePipe
and on to the UpperCasePipe
so we can display the birthday in uppercase. The following birthday displays as
APR 15, 1988.
This example — which displays FRIDAY, APRIL 15, 1988 —
chains the same pipes as above, but passes in a parameter to date
as well.
Custom Pipes
We can write our own custom pipes.
Here's a custom pipe named ExponentialStrengthPipe
that can boost a hero's powers:
lib/exponential_strength_pipe.dart
This pipe definition reveals several key points:
A pipe is a class decorated with pipe metadata.
The pipe class implements the
PipeTransform
interface'stransform
method that accepts an input value followed by optional parameters and returns the transformed value.There will be one additional argument to the
transform
method for each parameter passed to the pipe. Our pipe has one such parameter: theexponent
.We tell Angular that this is a pipe by applying the
@Pipe
annotation which we import from the core Angular library.The
@Pipe
annotation allows us to define the pipe name that we'll use within template expressions. It must be a valid JavaScript identifier. Our pipe's name isexponentialStrength
.
The PipeTransform Interface
The transform
method is essential to a pipe.
The PipeTransform
interface defines that method and guides both tooling and the compiler.
It is technically optional; Angular looks for and executes the transform
method regardless.
Now we need a component to demonstrate our pipe.
lib/power_booster_component.dart
Two things to note:
We use our custom pipe the same way we use the built-in pipes.
We must include our pipe in the
pipes
list of the@Component
annotation.
Angular reports an error if we neglect to list our custom pipe.
We didn't list the DatePipe
in our previous example because all
Angular built-in pipes are pre-registered.
Custom pipes must be registered manually.
If we try the
Power Boost Calculator (extra-credit)
It's not much fun updating the template to test our custom pipe.
We could upgrade the example to a "Power Boost Calculator" that combines
our pipe and two-way data binding with ngModel
.
/lib/power_boost_calculator_component.dart
Pipes and Change Detection
Angular looks for changes to data-bound values through a change detection process that runs after every JavaScript event: every keystroke, mouse move, timer tick, and server response. This could be expensive. Angular strives to lower the cost whenever possible and appropriate.
Angular picks a simpler, faster change detection algorithm when we use a pipe. Let's see how.
No pipe
The component in our next example uses the default, aggressive change detection strategy to monitor and update
its display of every hero in the heroes
list. Here's the template:
lib/flying_heroes_component.html (v1)
The companion component class provides heroes, adds new heroes into the list, and can reset the list.
lib/flying_heroes_component.dart (v1)
We can add a new hero and Angular updates the display when we do.
The reset
button replaces heroes
with a new list of the original heroes and Angular updates the display when we do.
If we added the ability to remove or change a hero, Angular would detect those changes too and update the display as well.
Flying Heroes pipe
Let's add a FlyingHeroesPipe
to the *ngFor
repeater that filters the list of heroes to just those heroes who can fly.
lib/flying_heroes_component.html (flyers)
Here's the FlyingHeroesPipe
implementation which follows the pattern for custom pipes we saw earlier.
lib/flying_heroes_pipe.dart
When we run the sample now we see odd behavior (try it in the
Although we're not getting the behavior we want, Angular isn't broken. It's just using a different change detection algorithm — one that ignores changes to the list or any of its items.
Look at how we're adding a new hero:
We're adding the new hero into the heroes
list. The reference to the list hasn't changed.
It's the same list. That's all Angular cares about. From its perspective, same list, no change, no display update.
We can fix that. Let's create a new list with the new hero appended and assign that to heroes
.
This time Angular detects that the list reference has changed.
It executes the pipe and updates the display with the new list which includes the new flying hero.
If we mutate the list, no pipe is invoked and no display updated; if we replace the list, then the pipe executes and the display is updated. The Flying Heroes extends the code with checkbox switches and additional displays to help us experience these effects.
Replacing the list is an efficient way to signal to Angular that it should update the display. When do we replace the list? When the data change. That's an easy rule to follow in this toy example where the only way to change the data is by adding a new hero.
More often we don't know when the data have changed, especially in applications that mutate data in many ways, perhaps in application locations far away. A component in such an application usually can't know about those changes. Moreover, it's unwise to distort our component design to accommodate a pipe. We strive as much as possible to keep the component class independent of the HTML. The component should be unaware of pipes.
Perhaps we should consider a different kind of pipe for filtering flying heroes, an impure pipe.
Pure and Impure Pipes
There are two categories of pipes: pure and impure.
Pipes are pure by default. Every pipe we've seen so far has been pure.
We make a pipe impure by setting its pure flag to false. We could make the FlyingHeroesPipe
impure like this:
Before we do that, let's understand the difference between pure and impure, starting with a pure pipe.
Pure pipes
Angular executes a pure pipe only when it detects a pure change to the input value. In Angular Dart, a pure change results only from a change in object reference (given that everything is an object in Dart).
Angular ignores changes within (composite) objects. It won't call a pure pipe if we change an input month, add to an input list, or update an input object property.
This may seem restrictive but is is also fast. An object reference check is fast — much faster than a deep check for differences — so Angular can quickly determine if it can skip both the pipe execution and a view update.
For this reason, we prefer a pure pipe if we can live with the change detection strategy. When we can't, we may turn to the impure pipe.
Or we might not use a pipe at all. It may be better to pursue the pipe's purpose with a property of the component, a point we take up later.
Impure pipes
Angular executes an impure pipe during every component change detection cycle. An impure pipe will be called a lot, as often as every keystroke or mouse-move.
With that concern in mind, we must implement an impure pipe with great care. An expensive, long-running pipe could destroy the user experience.
An impure FlyingHeroesPipe
A flip of the switch turns our FlyingHeroesPipe
into a FlyingHeroesImpurePipe
.
Here's the complete implementation:
We inherit from FlyingHeroesPipe
to prove the point that nothing changed internally.
The only difference is the pure
flag in the pipe metadata.
This is a good candidate for an impure pipe because the transform
function is trivial and fast.
lib/flying_heroes_component.dart (FlyingHeroesImpureComponent)
The only substantive change is the pipe in the template.
We can confirm in the heroes
list.
The impure AsyncPipe
The Angular AsyncPipe
is an interesting example of an impure pipe.
The AsyncPipe
accepts a Future
or Stream
as input
and subscribes to the input automatically, eventually returning the emitted value(s).
It is also stateful.
The pipe maintains a subscription to the input Stream
and
keeps delivering values from that Stream
as they arrive.
In this next example, we bind an Stream
of message strings
(message
) to a view with the async
pipe.
lib/hero_async_message_component.dart
The Async pipe saves boilerplate in the component code. The component doesn't have to subscribe to the async data source, it doesn't extract the resolved values and expose them for binding, and the component doesn't have to unsubscribe when it is destroyed (a potent source of memory leaks).
An impure caching pipe
Let's write one more impure pipe, a pipe that makes an HTTP request to the server. Normally, that's a horrible idea. It's probably a horrible idea no matter what we do. We're forging ahead anyway to make a point. Remember that impure pipes are called every few microseconds. If we're not careful, this pipe will punish the server with requests.
We are careful. Our pipe only makes a server call if the request URL has changed. It caches the request URL and waits for a result which it also caches when it arrives. The pipe returns the cached result (which is null while a request is in flight) after every Angular call and only contacts the server as necessary.
Here's the code, which uses the Angular http facility
to retrieve a heroes.json
file:
lib/fetch_json_pipe.dart
Then we demonstrate it in a harness component whose template defines two bindings to this pipe.
lib/hero_list_component.dart (template)
Despite the two bindings and what we know to be frequent pipe calls, the nework tab in the browser developer tools confirms that there is only one request for the file.
The component renders like this:
JsonPipe
The second binding involving the FetchPipe
uses more pipe chaining.
We take the same fetched results displayed in the first binding
and display them again, this time in JSON format by chaining through to the built-in JsonPipe
.
The JsonPipe provides an easy way to diagnosis a mysteriously failing data binding or inspect an object for future binding.
Here's the complete component implementation:
lib/hero_list_component.dart
Pure pipes and pure functions
A pure pipe uses pure functions. Pure functions process inputs and return values without detectable side-effects. Given the same input they should always return the same output.
The pipes we saw earlier in this chapter were implemented with pure functions.
The built-in DatePipe
is a pure pipe with a pure function implementation.
So is our ExponentialStrengthPipe
.
So is our FlyingHeroesPipe
.
A few steps back we reviewed the FlyingHeroesImpurePipe
— an impure pipe with a pure function.
But a pure pipe must always be implemented with a pure function. Failure to heed this warning will bring about many a console errors regarding expressions that have changed after they were checked.
Next Steps
Pipes are a great way to encapsulate and share common display-value transformations. We use them like styles, dropping them into our templates expressions to enrich the appeal and usability of our views.
Explore Angular's inventory of built-in pipes in the API Reference. Try writing a custom pipe and perhaps contributing it to the community.
No FilterPipe or OrderByPipe
Angular does not ship with pipes for filtering or sorting lists.
Developers familiar with Angular 1 know these as filter
and orderBy
.
There are no equivalents in Angular 2.
This is not an oversight. Angular 2 is unlikely to offer such pipes because
(a) they perform poorly and (b) they prevent aggressive minification.
Both filter
and orderBy
require parameters that reference object properties.
We learned earlier that such pipes must be impure and that
Angular calls impure pipes in almost every change detection cycle.
Filtering and especially sorting are expensive operations.
The user experience can degrade severely for even moderate sized lists when Angular calls these pipe methods many times per second.
The filter
and orderBy
have often been abused in Angular 1 apps, leading to complaints that Angular itself is slow.
That charge is fair in the indirect sense that Angular 1 prepared this performance trap
by offering filter
and orderBy
in the first place.
The minification hazard is also compelling if less obvious. Imagine a sorting pipe applied to a list of heroes.
We might sort the list by hero name
and planet
of origin properties something like this:
We identify the sort fields by text strings, expecting the pipe to reference a property value by indexing
(e.g., hero['name']
).
Unfortunately, aggressive minification munges the Hero
property names so that Hero.name
and Hero.planet
becomes something like Hero.a
and Hero.b
. Clearly hero['name']
is not going to work.
Some of us may not care to minify this aggressively. That's our choice. But the Angular product should not prevent someone else from minifying aggressively. Therefore, the Angular team decided that everything shipped in Angular will minify safely.
The Angular team and many experienced Angular developers strongly recommend that you move
filtering and sorting logic into the component itself.
The component can expose a filteredHeroes
or sortedHeroes
property and take control
over when and how often to execute the supporting logic.
Any capabilities that you would have put in a pipe and shared across the app can be
written in a filtering/sorting service and injected into the component.
If these performance and minification considerations do not apply to you, you can always create your own such pipes (along the lines of the FlyingHeroesPipe) or find them in the community.