您的位置:首页 > Web前端 > AngularJS

Angular2 中管道@Pipe的简单用法

2017-12-08 14:33 585 查看
在Angular2中有各种各样的类修饰器,比如:@App,@Component,@input,@output等等,最近需要用到数据过滤用到了管道@Pipe,下面记录简单@Pipe的简单用法。

Pipe(管道)官网传送门

什么是@Pipe(管道)?

其实这是一个过滤器的修饰声明,和Angular1中的filter的作用是一样的,有了filter能对数据处理提供强大的通用性和便利性,不过从Angular1到Angular2发生了巨大的转变,到了Angular2使用@Pipe是等同于Angular1中的filter,名字变化了而已。

@Pipe基本语法

import { Pipe } from 'angular2/core'

@Pipe({
name: 'pipe'  // 使用时的名称
})
export class TestPipe{
/**
* @description 具体处理方法的实现
* @param value 待处理的数据
* @param args 附加参数
* @return 处理完成的数据
*/
transform(value, args) {
return value;
}
}


Angular1中的filter

.filter('hello', function() {
return function(value) {
return 'Hello ' + value;
}
});


Angular2中的@Pipe

import { Pipe } from 'angular2/core'

@Pipe({
name: 'Neo'
})
export class HelloPipe {
transform( value ) {
return "Hello " + value;
}
}


两者在页面中使用基本一致

<!-- html -->
<span>{{ 'Neo' | hello }}<span>  <!-- 输出Hello 'Neo' -->


完整的Angular2@Pipe的使用方法如下:

1、声明一个管道ts,用于进行运算( calculate.pipe.ts )

// 导入模块
import {Pipe, PipeTransform} from "@angular/core";
// 管道名称
@Pipe({
name: "calculatePipe"
})
export class CalculatePipe implements PipeTransform {
// 参数说明:
// value是在使用管道的时候,获取的所在对象的值
// 后面可以跟若干个参数
// arg: 自定义参数, 数字类型, 使用的时候, 使用冒号添加在管道名称后面
transform(value:number, arg:number) {
return value * 10 * arg;
}
}


2、在app.module.ts主模块中引入管道

...
import { CalculatePipe } from "../pipe/calculate.pipe";
@ngModule({
declarations: [
CalculatePipe
]
})
...


3、组件模板中使用

<p>@Pipe管道的例子</p>
<p>
<input type="text" [(ngModel)]="number" name="number" class="form-control"/>
</p>
<!-- 不仅获取当前值,而且传递了一个参数,使用冒号添加到后面 -->
<p>{{ number | calculatePipe : 10 }}</p>




Angular2 中的一些内置管道:

五种内置管道,以及Angular官方的介绍

PipeUsageExample
DatePipedate{{ dateObj | date }} // output is ‘December 8, 2017’
UpperCasePipeuppercase{{ value | uppercase }} // output is ‘SOME TEXT’
LowerCasePipelowercase{{ value | lowercase }} // output is ‘some text’
CurrencyPipecurrency{{ 30.00 | currency:’USD’:true }} // output is ‘$30’
PercentPipepercent{{ 0.1 | percent }} //output is 10%
参考资料如下:

https://angular.io/guide/pipes

http://blog.csdn.net/u010730126/article/details/60370716

https://segmentfault.com/a/1190000008262691
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息