# 使用参数和管道链来格式化数据
可以用可选参数微调管道的输出。比如,你可以使用 CurrencyPipe 和国家代码(如 EUR)作为参数。模板表达式 amount | currency:'EUR'会把 amount转换成欧元。紧跟在管道名称(currency)后面的是冒号(:)和参数值('EUR')。
如果管道能接受多个参数,就用冒号分隔这些值。比如,amount | currency:'EUR':'Euros '会把第二个参数(字符串 'Euros ')添加到输出字符串中。你可以使用任何有效的模板表达式作为参数,比如字符串字面量或组件的属性。
有些管道需要至少一个参数,并且允许使用更多的可选参数,比如 SlicePipe 。比如,slice:1:5会创建一个新数组或字符串,它以第 1个元素开头,并以第 5个元素结尾。
# 范例:格式化日期
下面的例子显示了两种不同格式('shortDate'和 'fullDate')之间的切换:
该
app.component.html模板使用DatePipe(名为date)的格式参数把日期显示为 04/15/88。hero-birthday2.component.ts组件把该管道的 format 参数绑定到template中组件的format属性,并添加了一个按钮,其 click 事件绑定到了该组件的toggleFormat()方法。hero-birthday2.component.ts组件的toggleFormat()方法会在短格式('shortDate')和长格式('fullDate')之间切换该组件的format属性。
src/app/app.component.html
<p>The hero's birthday is {{ birthday | date:"MM/dd/yy" }} </p>
src/app/hero-birthday2.component.ts (template)
template: `
<p>The hero's birthday is {{ birthday | date:format }}</p>
<button type="button" (click)="toggleFormat()">Toggle Format</button>
`
src/app/hero-birthday2.component.ts (class)
export class HeroBirthday2Component {
birthday = new Date(1988, 3, 15); // April 15, 1988 -- since month parameter is zero-based
toggle = true; // start with true == shortDate
get format() { return this.toggle ? 'shortDate' : 'fullDate'; }
toggleFormat() { this.toggle = !this.toggle; }
}
点击 Toggle Format按钮可以在 04/15/1988和 Friday, April 15, 1988之间切换日期格式。
关于 date管道的格式选项,参阅 DatePipe 。
# 范例:通过串联管道应用两种格式
可以对管道进行串联,以便一个管道的输出成为下一个管道的输入。
在下面的范例中,串联管道首先将格式应用于一个日期值,然后将格式化之后的日期转换为大写字符。src/app/app.component.html模板的第一个标签页把 DatePipe和 UpperCasePipe的串联起来,将其显示为 APR 15, 1988。src/app/app.component.html模板的第二个标签页在串联 uppercase之前,还把 fullDate参数传给了 date,将其显示为 FRIDAY, APRIL 15, 1988。
src/app/app.component.html (1)
The chained hero's birthday is
{{ birthday | date | uppercase}}
src/app/app.component.html (2)
The chained hero's birthday is
{{ birthday | date | uppercase}}