什么是管道
还记得第一次接触到 管道 这个概念是在linux终端命令中,通过管道使用grep命令对内容进行过滤。
cat test.txt | grep "pipe"
使用 | 表示创建了一个管道。
值得庆幸的,在Angular的管道和linux中的相似。管道把数据作为输入,然后进行转化处理,并输出转化后的结果。
import { Component } from '@angular/core';@Component({selector: 'app-hero-birthday',template: `<p>The hero's birthday is {{ birthday | date }}</p>`})export class HeroBirthdayComponent {birthday = new Date(1988, 3, 15); // April 15, 1988}
在上面的例子中, date 就是Angular内置的日期管道。管道操作符( | ),表示数据从左流动到右侧的date管道中。
内置管道
AsyncPipe
异步管道,用于Observable | Promise 对象。从一个异步回执中解出一个值。
@Component({selector: 'async-observable-pipe',template: '<div><code>observable|async</code>: Time: {{ time | async }}</div>'})export class AsyncObservablePipeComponent {time = new Observable<string>((observer: Observer<string>) => {setInterval(() => observer.next(new Date().toString()), 1000);});}
CurrencyPipe
把数字转换成金额字符串, 根据本地化规则进行格式化,这些规则会决定分组大小和分组分隔符、小数点字符以及其它与本地化环境有关的配置项。
{{ value_expression | currency [ : currencyCode [ : display [ : digitsInfo [ : locale ] ] ] ] }}
@Component({selector: 'currency-pipe',template: `<div><!--output '$0.26'--><p>A: {{a | currency}}</p><!--output 'CA$0.26'--><p>A: {{a | currency:'CAD'}}</p><!--output 'CAD0.26'--><p>A: {{a | currency:'CAD':'code'}}</p><!--output 'CA$0,001.35'--><p>B: {{b | currency:'CAD':'symbol':'4.2-2'}}</p><!--output '$0,001.35'--><p>B: {{b | currency:'CAD':'symbol-narrow':'4.2-2'}}</p><!--output '0 001,35 CA$'--><p>B: {{b | currency:'CAD':'symbol':'4.2-2':'fr'}}</p><!--output 'CLP1' because CLP has no cents--><p>B: {{b | currency:'CLP'}}</p></div>`})export class CurrencyPipeComponent {a: number = 0.259;b: number = 1.3495;}
DatePipe
DecimalPipe
LowerCasePipe
PercentPipe
SlicePipe
TitleCasePipe
UpperCasePipe
自定义管道
在Angular中使用@Pipe装饰器来创建一个管道。
import { Pipe, PipeTransform } from '@angular/core';/** Raise the value exponentially* Takes an exponent argument that defaults to 1.* Usage:* value | exponentialStrength:exponent* Example:* {{ 2 | exponentialStrength:10 }}* formats to: 1024*/@Pipe({name: 'exponentialStrength'})export class ExponentialStrengthPipe implements PipeTransform {transform(value: number, exponent?: number): number {return Math.pow(value, isNaN(exponent) ? 1 : exponent);}}
