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 arrives, you could push their raw toString values directly to the view, but that rarely makes for a good user experience. For example, in most use cases, users prefer to see a date in a simple format like April 15, 1988 rather than the raw string format Fri Apr 15 1988 00:00:00 GMT-0700 (Pacific Daylight Time).

Clearly, some values benefit from a bit of editing. You may notice that you desire many of the same transformations repeatedly, both within and across many applications. You can almost think of them as styles. In fact, you might like to apply them in your HTML templates as you do styles.

通过引入 Angular 管道（一种编写"从显示到值"转换逻辑的途径），你可以把它声明在 HTML 中。

Introducing Angular pipes, a way to write display-value transformations that you can declare in your HTML.

A pipe can accept any number of optional parameters to fine-tune its output. To add parameters to a pipe, follow the pipe name with a colon ( : ) and then the parameter value (such as currency:'EUR'). If the pipe accepts multiple parameters, separate the values with colons (such as slice:1:5)

修改生日模板，来为这个日期管道提供一个格式化参数。 当格式化完该英雄的 4 月 15 日生日之后，它应该被渲染成04/15/88。

Modify the birthday template to give the date pipe a format parameter. After formatting the hero's April 15th birthday, it renders as 04/15/88:

The parameter value can be any valid template expression, (see the Template expressions section of the Template Syntax page) such as a string literal or a component property. In other words, you can control the format through a binding the same way you control the birthday value through a binding.

来写第二个组件，它把管道的格式参数绑定到该组件的 format 属性。这里是新组件的模板：

Write a second component that binds the pipe's format parameter to the component's format property. Here's the template for that component:

You 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').

You can chain pipes together in potentially useful combinations. In the following example, to display the birthday in uppercase, the birthday is chained to the DatePipe and on to the UpperCasePipe. The birthday displays as APR 15, 1988.

The transform method is essential to a pipe. The PipeTransforminterface defines that method and guides both tooling and the compiler. Technically, it's optional; Angular looks for and executes the transform method regardless.

Angular looks for changes to data-bound values through a change detection process that runs after every DOM 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 会选用一种更简单、更快速的变更检测算法。

Angular picks a simpler, faster change detection algorithm when you use a pipe.

You can add heroes and Angular updates the display when you do. If you click the reset button, Angular replaces heroes with a new array of the original heroes and updates the display. If you added the ability to remove or change a hero, Angular would detect those changes and update the display as well.

To fix that, create an array with the new hero appended and assign that to heroes. This time Angular detects that the array reference has changed. It executes the pipe and updates the display with the new array, which includes the new flying hero.

If you mutate the array, no pipe is invoked and the display isn't updated; if you replace the array, the pipe executes and the display is updated. The Flying Heroes application extends the code with checkbox switches and additional displays to help you experience these effects.

Replacing the array is an efficient way to signal Angular to update the display. When do you replace the array? When the data changes. That's an easy rule to follow in this example where the only way to change the data is by adding a hero.

More often, you don't know when the data has 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 the component design to accommodate a pipe. Strive to keep the component class independent of the HTML. The component should be unaware of pipes.

There are two categories of pipes: pure and impure. Pipes are pure by default. Every pipe you've seen so far has been pure. You make a pipe impure by setting its pure flag to false. You could make the FlyingHeroesPipe impure like this:

Angular executes a pure pipe only when it detects a pure change to the input value. A pure change is either a change to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object).

This may seem restrictive but it's 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, a pure pipe is preferable when you can live with the change detection strategy. When you can't, you can use the impure pipe.

或者你也可以完全不用管道。 有时候，使用组件的属性能比用管道更好的达到目的，后面会再讨论这一点。

Or you 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 that's discussed later in this page.

The Angular AsyncPipe is an interesting example of an impure pipe. The AsyncPipe accepts a Promise or Observable as input and subscribes to the input automatically, eventually returning the emitted values.

The Async pipe saves boilerplate in the component code. The component doesn't have to subscribe to the async data source, extract the resolved values and expose them for binding, and have to unsubscribe when it's destroyed (a potent source of memory leaks).

The pipes discussed earlier in this page are implemented with pure functions. The built-in DatePipe is a pure pipe with a pure function implementation. So are the ExponentialStrengthPipe and FlyingHeroesPipe. A few steps back, you reviewed the FlyingHeroesImpurePipe—an impure pipe with a pure function.

但是一个纯管道必须总是用纯函数实现。忽略这个警告将导致失败并带来一大堆这样的控制台错误：表达式在被检查后被变更。

But always implement a pure pipe with a pure function. Otherwise, you'll see many console errors regarding expressions that changed after they were checked.

Pipes are a great way to encapsulate and share common display-value transformations. Use them like styles, dropping them into your template's expressions to enrich the appeal and usability of your views.

This isn't an oversight. Angular doesn't offer such pipes because they perform poorly and prevent aggressive minification. Both filter and orderBy require parameters that reference object properties. Earlier in this page, you learned 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. filter and orderBy have often been abused in AngularJS apps, leading to complaints that Angular itself is slow. That charge is fair in the indirect sense that AngularJS 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. The list might be sorted by hero name and planet of origin properties in the following way:

You identify the sort fields by text strings, expecting the pipe to reference a property value by indexing (such as hero['name']). Unfortunately, aggressive minification manipulates the Hero property names so that Hero.name and Hero.planet become something like Hero.a and Hero.b. Clearly hero['name'] doesn't work.

While some may not care to minify this aggressively, the Angular product shouldn't prevent anyone from minifying aggressively. Therefore, the Angular team decided that everything Angular provides will minify safely.

The Angular team and many experienced Angular developers strongly recommend moving 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.