1. 管道操作符 |
import { Component } from '@angular/core';@Component({selector: 'app-hero-birthday',template: `<p>The hero's birthday is {{ birthday | date }}</p>` //The hero's birthday is 1988年4月15日})export class HeroBirthdayComponent {birthday = new Date(1988, 3, 15); // April 15, 1988}
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” }}
import { Component } from '@angular/core';@Component({selector: 'app-hero-birthday',template: ` <p>The hero's birthday is {{ birthday | date:format }}</p><button (click)="toggleFormat()">Toggle Format</button>`})export class HeroBirthdayComponent {birthday = new Date(1988, 3, 15); // April 15, 1988toggle = true; // start with true == shortDateget format() { return this.toggle ? 'shortDate' : 'fullDate'; }toggleFormat() { this.toggle = !this.toggle; }}
4. 链式管道
<p>The chained hero's birthday is{{ birthday | date | uppercase}}</p>
5. 自定义管道
import { Pipe, PipeTransform } from '@angular/core';@Pipe({name: 'exponentialStrength'}) // pipe装饰器定义管道名:如DataPipeexport class ExponentialStrengthPipe implements PipeTransform {transform(value: number, exponent?: number): number { // transform:管道的基本要素 exponent 可选参数 如 Date:"MM/dd/yy"return Math.pow(value, isNaN(exponent) ? 1 : exponent);}}
注意:要添加到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. 能力倍增计算器
和双向数据绑定组合使用
import { Component } from '@angular/core';@Component({selector: 'app-power-boost-calculator',template: `<h2>Power Boost Calculator</h2><div>Normal power: <input [(ngModel)]="power"></div><div>Boost factor: <input [(ngModel)]="factor"></div><p>Super Hero Power: {{power | exponentialStrength: factor}}</p>`})export class PowerBoostCalculatorComponent {power = 5;factor = 1;}
- 管道与变更检测
- 纯管道和非纯管道
pure标志设置为false
@Pipe({name: 'flyingHeroesImpure',pure: false})
