管道把数据作为输入,然后转换它,给出期望的输出。 我们将把组件的birthday
属性转换成对人类更友好的日期格式,来说明这一点:
app/hero-birthday1.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'hero-birthday',
template: `<p>The hero's birthday is {{ birthday | date }}</p>`
})
export class HeroBirthdayComponent {
birthday = new Date(1988, 3, 15); // April 15, 1988
}
重点看下组件的模板。
<p>The hero's birthday is {{ birthday | date }}</p>
在这个插值表达式中,我们让组件的birthday
值通过管道操作符( | )流动到 右侧的Date管道函数中。所有管道都会用这种方式工作。
Date
和Currency
管道需要ECMAScript国际化(I18n)API,但Safari和其它老式浏览器不支持它,该问题可以用垫片(Polyfill)解决。
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.en"></script>
内置的管道
Angular内置了一些管道,比如DatePipe
、UpperCasePipe
、LowerCasePipe
、CurrencyPipe
和PercentPipe
。 它们全都可以直接用在任何模板中。
对管道进行参数化
管道可能接受任何数量的可选参数来对它的输出进行微调。 我们可以在管道名后面添加一个冒号( : )再跟一个参数值,来为管道添加参数(比如currency:'EUR'
)。 如果我们的管道可以接受多个参数,那么就用冒号来分隔这些参数值(比如slice:1:5
)。
我们将通过修改生日模板来给这个日期管道提供一个格式化参数。 当格式化完该英雄的4月15日生日之后,它应该被渲染成04/15/88。
<p>The hero's birthday is {{ birthday | date:"MM/dd/yy" }} </p>
参数值可以是任何有效的模板表达式,比如字符串字面量或组件的属性。 换句话说,借助属性绑定,我们也可以像用绑定来控制生日的值一样,控制生日的显示格式。
我们来写第二个组件,它把管道的格式参数绑定到该组件的format
属性。这里是新组件的模板:
app/hero-birthday2.component.ts (template)
template: `
<p>The hero's birthday is {{ birthday | date:format }}</p>
<button (click)="toggleFormat()">Toggle Format</button>
`
我们还能在模板中添加一个按钮,并把它的点击事件绑定到组件的toggleFormat()
方法。 此方法会在短日期格式('shortDate'
)和长日期格式('fullDate'
)之间切换组件的format
属性。
app/hero-birthday2.component.ts (class)
export class HeroBirthday2Component {
birthday = new Date(1988, 3, 15); // April 15, 1988
toggle = true; // start with true == shortDate
get format() { return this.toggle ? 'shortDate' : 'fullDate'; }
toggleFormat() { this.toggle = !this.toggle; }
}
当我们点击按钮的时候,显示的日志会在"04/15/1988"和"Friday, April 15, 1988"之间切换。
要了解更多DatePipes
的格式选项,请参阅API文档。
链式管道
我们可以把管道链在一起,以组合出一些潜在的有用功能。 下面这个例子中,我们把birthday
链到DatePipe
管道,然后又链到UpperCasePipe
,这样我们就可以把生日显示成大写形式了。 比如下面的代码就会把生日显示成APR 15, 1988:
The chained hero's birthday is
{{ birthday | date | uppercase}}
下面这个显示FRIDAY, APRIL 15, 1988的例子用同样的方式链接了这两个管道,而且同时还给date
管道传进去一个参数。
The chained hero's birthday is
{{ birthday | date:'fullDate' | uppercase}}