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的更多相关文章

  1. angular2 pipe实现搜索结果中的搜索关键字高亮

    效果图如下 1.声明一个pipe import {Pipe, Injectable, PipeTransform} from '@angular/core';import { DomSanitizer ...

  2. 4、Angular2 pipe

    1. stateless pipe 2.stateful pipe

  3. [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 ...

  4. [Angular 2] Pipe Purity

    Explaining how Pipes only change by default when your Pipe input parameters change and not when your ...

  5. ASP.NET MVC和Web API中的Angular2 - 第2部分

    下载源码 内容 第1部分:Visual Studio 2017中的Angular2设置,基本CRUD应用程序,第三方模态弹出控件 第2部分:使用Angular2管道进行过滤/搜索,全局错误处理,调试客 ...

  6. [Angular 2] Pipes with Multiple Parameters

    Showing how to set up a Pipe that takes multiple updating inputs for multiple Component sources. imp ...

  7. [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 ...

  8. 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 ...

  9. ionic2 目录

    首先 ionic2 暂时找不到中文文档.本人英语又很渣.无奈之下只能依赖于百度翻译.完全是已自己理解的方式运作 ,可能里面会有一些偏差之类的 不过我都测试过代码是可以跑通的 只不过讲解的部分可能... ...

随机推荐

  1. ios手势识别代理

    之前做优质派时写了个仿网易新闻导航的第三方,由于当时做项目时这个主控制器就是RootViewController,虽然用的是ScrollView但也没考虑到导航栏的手势返回的问题 ,现在做小区宝3.0 ...

  2. Delphi 枚举所有进程

    通过进程快照枚举所有进程,关于进程快照,在Delphi5开发人员指南中有说明,当然也可以百度一下用法. 使用进程快照CreateToolhelp32Snapshot,必须uses TlHelp32单元 ...

  3. C# 之构造函数

    构造函数是一种特殊的成员函数,它主要用于为对象分配存储空间,对数据成员进行初始化. 构造函数具有一些特殊的性质: (1)构造函数的名字必须与类同名; (2)构造函数没有返回类型,它可以带参数,也可以不 ...

  4. golang类型转化

     int 转 float mean:= float32(sum)   float 转 int a := 5.0 b := int(a)   string 转 int i,_ := strconv.At ...

  5. async和await理解代码

    <1>:Async和Await的理解1 using System; using System.Collections.Generic; using System.Linq; using S ...

  6. 使用 OLEDB 及 SqlBulkCopy 将多个不在同一文件夹下的 ACCESS mdb 数据文件导入MSSQL

    注:转载请标明文章原始出处及作者信息http://www.cnblogs.com/z-huifei/p/7380388.html 前言 OLE DB 是微软的战略性的通向不同的数据源的低级应用程序接口 ...

  7. sprintf 格式化字符串

    好久没写博客了,又遇到自己觉得很傻的问题,格式化字符串还要找下 定义和用法 sprintf() 函数把格式化的字符串写入变量中. arg1.arg2.++ 参数将被插入到主字符串中的百分号(%)符号处 ...

  8. ajax success和error接收了哪些状态码

    ajax和 Http Status 之前一直奇怪ajax发送请求后success 和 error 分界的状态码是多少, 主要很多将ajax的教程也没有提到, 例如, 我用ResponseEntity& ...

  9. hdu 2049 考新郎

    假设一共有N对新婚夫妇,其中有M个新郎找错了新娘,求发生这种情况一共有多少种可能. 和之前那道题一样,是错排,但是要乘上排列数. 选对的人有C(N,M)个组合,将它们排除掉,剩下的人就是错排了 #in ...

  10. Mac Iterm 或者自带终端 bogon:~ username$

    mac 在用Iterm2 遇到命令行前缀自带 bogon:~ username$ 太长问题.有代码洁癖的我,终于找到了解决办法. 具体问题见下图: 而我想要的结果是: 解决办法:是安装 Oh My Z ...