Angular2 Pipe
AngularJs 1.x 中使用filters来帮助我们转换templates中的输出,但在Angular2中使用的是pipes,以下展示Angular 1.x and Angular 2中filter和pipe的对比:
| Filter/Pipe Name | Angular 1.x | Angular 2 |
|---|---|---|
| currency | ✓ | ✓ |
| date | ✓ | ✓ |
| uppercase | ✓ | ✓ |
| json | ✓ | ✓ |
| limitTo | ✓ | ✓ |
| lowercase | ✓ | ✓ |
| number | ✓ | |
| orderBy | ✓ | |
| filter | ✓ | |
| async | ✓ | |
| decimal | ✓ | |
| percent | ✓ |
Basic Pipes
// app.ts
// <reference path="typings/angular2/angular2.d.ts" />
import {Component, View, bootstrap} from 'angular2/angular2';
@Component({
selector: 'pipes'
})
@View({
templateUrl: 'pipesTemplate.html'
})
// Component controller
class PipesAppComponent {
date: Date;
constructor() {
this.date = new Date();
}
}
bootstrap(PipesAppComponent);
<!-- pipesTemplate.html -->
<h1>Dates</h1>
<!-- Sep 1, 2015 -->
<p>{{date | date:'mediumDate'}}</p>
<!-- September 1, 2015 -->
<p>{{date | date:'yMMMMd'}}</p>
<!-- 3:50 pm -->
<p>{{date | date:'shortTime'}}</p>
结果:

New Pipes
decimal和percent是Angular2中新增的管道,参数规则是:{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}.
decimal管道在模板中使用number关键字
// app.ts
...
@View({
templateUrl: 'pipesTemplate.html'
})
class PipesAppComponent {
grade: number;
rating: number;
constructor() {
this.grade = 0.99;
this.rating = 9.1243;
}
}
...
html
<h1>Decimals/Percentages</h1>
<!-- 99.00% -->
<p>{{grade | percent:'.2'}}</p>
<!-- 09.12 -->
<p>{{rating | number:'2.1-2'}}</p>
结果:

Async Pipe
Angular 2's async allows us to bind our templates directly to values that arrive asynchronously. This ability is great for working with promises and observables.
// app.ts
...
@Component({
selector: 'pipes',
changeDetection: 'ON_PUSH'
})
@View({
templateUrl: 'pipesTemplate.html',
})
class PipesAppComponent {
promise: Promise;
constructor() {
this.promise = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve("Hey, I'm from a promise.");
}, 2000)
});
}
}
...
html
<!-- pipesTemplate.html -->
<h1>Async</h1>
<p>{{ promise | async}}</p>
After a 2 second delay, the value from the resolved promise will be displayed on the screen.

Custom Pipes
自定义pipe需要使用@Pipe装饰器,并实现PipeTransform接口里的transform方法。定义好的pipe要在需使用pipe的view或component中声明。
Pipe接口的定义
export interface Pipe {
name: string;
pure?: boolean;
}
PipeDecorator
export const Pipe: PipeDecorator = <PipeDecorator>makeDecorator('Pipe', {
name: undefined,
pure: true, // 默认是pure
});
PipeTransform接口
export interface PipeTransform {
transform(value: any, ...args: any[]): any;
}
管道分类
pure 管道:仅当管道输入值变化的时候,才执行转换操作,默认的类型是 pure 类型。(备注:输入值变化是指原始数据类型如:string、number、boolean 等的数值或对象的引用值发生变化)
impure 管道:在每次变化检测期间都会执行,如鼠标点击或移动都会执行 impure 管道
// app.ts
import {Component, View, bootstrap, Pipe, PipeTransform} from 'angular2/angular2';
...
// We use the @Pipe decorator to register the name of the pipe
@Pipe({
name: 'tempConvert'
})
// The work of the pipe is handled in the tranform method with our pipe's class
class TempConvertPipe implements PipeTransform {
transform(value: number, args: any[]) {
if(value && !isNaN(value) && args[0] === 'celsius') {
var temp = (value - 32) * 5/9;
var places = args[1];
return temp.toFixed(places) + ' C';
}
return;
}
}
...
@View({
templateUrl: 'pipesTemplate.html',
// We can pass the pipe class name into the pipes key to make it usable in our views
pipes: [TempConvertPipe]
})
class PipesAppComponent {
temperature: number;
constructor() {
this.temperature = 85;
}
}
html
<h1>Custom Pipes - Convert Temperature</h1>
<!-- 85 F -->
<h3>Fahrenheit: {{temperature + ' F'}}</h3>
<!-- 29.4 C -->
<h3>Celsius: {{temperature | tempConvert:'celsius':1}}</h3>
结果

过滤出指定范围的值
定义一个pipe
import {Pipe, PipeTransform} from 'angular2/core';
// Tell Angular2 we're creating a Pipe with TypeScript decorators
@Pipe({
name: 'AgePipe'
})
export class AgePipe implements PipeTransform {
// Transform is the new "return function(value, args)" in Angular 1.x
transform(value, args?) {
// ES6 array destructuring
let [minAge, maxAge] = args;
return input.filter(person => {
return person.age >= +minAge && person.age <= +maxAge;
});
}
}
import {Component} from 'angular2/core';
import {AgePipe} from './pipes/age-pipe/age-pipe';
@Component({
selector: 'playground-app',
templateUrl: 'app/playground.html',
// tell our component it uses our AgePipe
pipes: [AgePipe]
})
export class PlaygroundApp {
sliderValue:number = 20;
anotherSliderValue: number = 90;
people:Array<any> = [{
name: 'Justin Bieber',
age: 21
}, {
name: 'Miley Cyrus',
age: 23
}, {
name: 'John Legend',
age: 37
}, {
name: 'Betty White',
age: 94
}, {
name: 'Roger Waters',
age: 72
}, {
name: 'Larry Page',
age: 42
}];
}
html
<div>
<p>
0
<input type="range" min="0" max="100"
[value]="sliderValue"
(input)="sliderValue = $event.target.value" />
100
</p>
<span>{{ sliderValue }}</span>
<p>
0
<input type="range" min="0" max="100"
[(ngModel)]="anotherSliderValue" />
100
</p>
<span>{{anotherSliderValue }}</span>
<ul>
<li *ngFor="#person of people | AgePipe:sliderValue:anotherSliderValue">
{{ person.name }} ({{ person.age }})
</li>
</ul>
</div>
Angular2 Pipe的更多相关文章
- angular2 pipe实现搜索结果中的搜索关键字高亮
效果图如下 1.声明一个pipe import {Pipe, Injectable, PipeTransform} from '@angular/core';import { DomSanitizer ...
- 4、Angular2 pipe
1. stateless pipe 2.stateful pipe
- [Angular 2] Create a simple search Pipe
This lesson shows you how to create a component and pass its properties as it updates into a Pipe to ...
- [Angular 2] Pipe Purity
Explaining how Pipes only change by default when your Pipe input parameters change and not when your ...
- ASP.NET MVC和Web API中的Angular2 - 第2部分
下载源码 内容 第1部分:Visual Studio 2017中的Angular2设置,基本CRUD应用程序,第三方模态弹出控件 第2部分:使用Angular2管道进行过滤/搜索,全局错误处理,调试客 ...
- [Angular 2] Pipes with Multiple Parameters
Showing how to set up a Pipe that takes multiple updating inputs for multiple Component sources. imp ...
- [Angular 2] Using Pipes to Filter Data
Pipes allow you to change data inside of templates without having to worry about changing it in the ...
- Angular 2 to Angular 4 with Angular Material UI Components
Download Source - 955.2 KB Content Part 1: Angular2 Setup in Visual Studio 2017, Basic CRUD applicat ...
- ionic2 目录
首先 ionic2 暂时找不到中文文档.本人英语又很渣.无奈之下只能依赖于百度翻译.完全是已自己理解的方式运作 ,可能里面会有一些偏差之类的 不过我都测试过代码是可以跑通的 只不过讲解的部分可能... ...
随机推荐
- c# 删除文件,清理删除文件
c# 删除程序占用的文件,清理删除文件,彻底删除文件,解除文件占用 文件打开时,以共享读写模式打开 FileStream inputStream = new FileStream(name, File ...
- DataGridView 隔行显示不同的颜色
两种方法 第一种 DataGridview1.Rows[i].DefultCellStyle.backcolor 第二种 AlternatingRowsDefutCellstyle 属性 获取或设置应 ...
- Timer控件
Timer控件是定期引发事件的控件,时间间隔的长度由interval属性定义,其值以毫秒为单位吗,若启用了该组件,则每个事件间隔引发一个Tick事件,Timer组件的主要方法包括start和stop, ...
- PHP反射ReflectionClass、ReflectionMethod 学习笔记 (一)
PHP5 具有完整的反射API,添加对类.接口.函数.方法和扩展进行反向工程的能力. 反射是什么? 它是指在PHP运行状态中,扩展分析PHP程序,导出或提取出关于类.方法.属性.参数等的详细信息,包括 ...
- [javaSE] IO流(对象序列化)
写入 获取ObjectOutputStream对象,new出来,构造参数:FileOutputStream对象目标文件 调用ObjectOutputStream对象的writeObject()方法,参 ...
- Golang把所有包括底层类库,输出到stderr的内容, 重新定向到一个日志文件里面?
不论应用是如何部署的,我们都期望能扑捉到应用的错误日志, 解决思路: 自己写代码处理异常拦截,甚至直接在main函数中写异常拦截. stderr重定向到某个文件里 使用 syscall.Dup2 第一 ...
- hdu 1159(DP+字符串最长公共序列)
http://blog.csdn.net/a_eagle/article/details/7213236 公共序列可以用一个二维数组dp[i][j]保存每个点时的最大数字,本质就是一个双向比较. dp ...
- python中静态方法(@staticmethod)和类方法(@classmethod)的区别
一般来说,要使用某个类的方法,需要先实例化一个对象再调用方法. 而使用@staticmethod或@classmethod,就可以不需要实例化,直接类名.方法名()来调用. 这有利于组织代码,把某些应 ...
- 洛谷P5057 [CQOI2006]简单题(线段树)
题意 题目链接 Sol 紫色的线段树板子题??... #include<iostream> #include<cstdio> #include<cmath> usi ...
- Sql语句常用关键字
--语 句 功 能--数据操作SELECT --从数据库表中检索数据行和列INSERT --向数据库表添加新数据行DELETE --从数据库表中删除数据行UPDATE --更新数据库表中的数据 --数 ...