angular中的日期管道:
{{ value_expression | date [ : format [ : timezone [ : locale ] ] ] }}
其中value为日期表达式,是一个Date对象、数字(从 UTC 时代以来的毫秒数)或一个 ISO 字符串 ;
format是一个要包含的日期、时间部分的格式,使用预定义选项或自定义格式字符串——
format包括:short、medium、long、full、shortDate、mediumDate、longDate、fullDate、shortTime、mediumTime、longTime、fullTime;
locale 是一个 string,用来定义要使用的区域;
timezone 用在格式化中。它能理解 UTC/GMT 和美国大陆时区缩写,但对于一般用途则使用时区偏移(比如 '+0430')。 如果没有指定,则使用宿主系统中的设定。
可选. 默认值是 'mediumDate'
.
详见:https://angular.cn/api/common/DatePipe
e.g:
{{ dateObj | date }} // output is 'Jun 15, 2015'
{{ dateObj | date:'medium' }} // output is 'Jun 15, 2015, 9:43:11 PM'
{{ dateObj | date:'shortTime' }} // output is '9:43 PM'
{{ dateObj | date:'mmss' }} // output is '43:11'
{{ birthday | date:"MM/dd/yy" }}
管道还可以组合成链式管道:比如日期格式大写:
{{ birthday | date: 'fullDate' | uppercase}}
关键点:
管道类实现了 PipeTransform 接口的 transform 方法,该方法接受一个输入值和一些可选参数,并返回转换后的值。当每个输入值被传给 transform 方法时,还会带上另一个参数。transform 方法是管道的基本要素。 PipeTransform 接口中定义了它,并用它指导各种工具和编译器。 理论上说,它是可选的。Angular 不会管它,而是直接查找并执行 transform 方法。
你必须在 AppModule 的 declarations 数组中包含这个管道!
e.g:自定义管道举例:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'exponentialStrength'})
export class ExponentialStrengthPipe implements PipeTransform {
transform(value: number, exponent: string): number {
let exp = parseFloat(exponent);
return Math.pow(value, isNaN(exp) ? 1 : exp);
} }
下面用组件来演示这个管道的使用:
import { Component } from '@angular/core'; 、
@Component({
selector: 'app-power-booster',
template: ` <h2>Power Booster</h2>
<p>Super power boost: {{2 | exponentialStrength: 10}}</p> `
})
export class PowerBoosterComponent { }
得到结果:(2的10次方)1024。