1. 管道操作符 |

  1. import { Component } from '@angular/core';
  2. @Component({
  3. selector: 'app-hero-birthday',
  4. template: `<p>The hero's birthday is {{ birthday | date }}</p>` //The hero's birthday is 1988年4月15日
  5. })
  6. export class HeroBirthdayComponent {
  7. birthday = new Date(1988, 3, 15); // April 15, 1988
  8. }

2. 内置的管道

管道 类型 功能
DatePipe 纯管道 日期格式化
JsonPipe 非纯管道 使用JSON.stringify()将对象转成json字符串
UpperCasePipe 纯管道 将文本中的字母全部转在大写
LowerCasePipe 纯管道 将文本中的字母全部转成小写
TitleCasePipe 将文本转换成标题格式
DecimalPipe 纯管道 数值格式化
CurrencyPipe 纯管道 货币格式化
PercentPipe 纯管道 百分比格式化
SlicePipe 非纯管道 数组或字符串取切割
I18nPluralPipe 根据expression的值匹配mapping中的值,并将匹配之后的值展示出来
I18nSelectPipe 根据expression匹配mapping中的值,并且返回匹配之后的值

3. 管道参数化

The hero’s birthday is {{ birthday | date:”MM/dd/yy” }}

  1. import { Component } from '@angular/core';
  2. @Component({
  3. selector: 'app-hero-birthday',
  4. template: ` <p>The hero's birthday is {{ birthday | date:format }}</p>
  5. <button (click)="toggleFormat()">Toggle Format</button>`
  6. })
  7. export class HeroBirthdayComponent {
  8. birthday = new Date(1988, 3, 15); // April 15, 1988
  9. toggle = true; // start with true == shortDate
  10. get format() { return this.toggle ? 'shortDate' : 'fullDate'; }
  11. toggleFormat() { this.toggle = !this.toggle; }
  12. }

4. 链式管道

  1. <p>The chained hero's birthday is
  2. {{ birthday | date | uppercase}}</p>

5. 自定义管道

  1. import { Pipe, PipeTransform } from '@angular/core';
  2. @Pipe({name: 'exponentialStrength'}) // pipe装饰器定义管道名:如DataPipe
  3. export class ExponentialStrengthPipe implements PipeTransform {
  4. transform(value: number, exponent?: number): number { // transform:管道的基本要素 exponent 可选参数 如 Date:"MM/dd/yy"
  5. return Math.pow(value, isNaN(exponent) ? 1 : exponent);
  6. }
  7. }

注意:要添加到AppModule的declarations数组中
如果选择将管道注入(inject)类中,则必须将管道包含字在[NgModule](https://angular.cn/api/core/NgModule)providers数组中。

6. Pipi Transform 接口

transform 方法是管道的基本要素。 [PipeTransform](https://angular.cn/api/core/PipeTransform)接口中定义了它,并用它指导各种工具和编译器。 理论上说,它是可选的。Angular 不会管它,而是直接查找并执行 transform 方法。

7. 能力倍增计算器

和双向数据绑定组合使用

  1. import { Component } from '@angular/core';
  2. @Component({
  3. selector: 'app-power-boost-calculator',
  4. template: `
  5. <h2>Power Boost Calculator</h2>
  6. <div>Normal power: <input [(ngModel)]="power"></div>
  7. <div>Boost factor: <input [(ngModel)]="factor"></div>
  8. <p>
  9. Super Hero Power: {{power | exponentialStrength: factor}}
  10. </p>
  11. `
  12. })
  13. export class PowerBoostCalculatorComponent {
  14. power = 5;
  15. factor = 1;
  16. }
  1. 管道与变更检测
  2. 纯管道和非纯管道

pure标志设置为false

  1. @Pipe({
  2. name: 'flyingHeroesImpure',
  3. pure: false
  4. })