angualr2中管道@pipe的简单使用

需求
使用过滤,实现前台查询。
在Angular2中有各种各样的类修饰器,比如:@App,@Component,@input,@output等等,最近需要用到数据过滤用到了管道@Pipe,下面记录简单@Pipe的简单用法。
什么是pipe?
就是管道,简单来说,管道的作用就是传输。并且不同的管道具有不同的作用。(其实就是处理数据)。

angualr中自带的pipe函数

管道
功能

DatePipe
日期管道,格式化日期

JsonPipe
将输入数据对象经过JSON.stringify()方法转换后输出对象的字符串

UpperCasePipe
将文本所有小写字母转换成大写字母

LowerCasePipe
将文本所有大写字母转换成小写字母

DecimalPipe
将数值按照特定的格式显示文本

CurrentcyPipe
将数值进行货币格式化处理

SlicePipe
将数组或者字符串裁剪成新子集

PercentPipe
将数值转百分比格式

pipe用法

{{ 输入数据 | 管道 : 管道参数}} (其中‘|’是管道操作符)
链式管道 {{ 输入数据 | date | uppercase}}

详细内容请参考angualr官方文档Angular-pipe

pipe的基本语法
import { Pipe, PipeTransform } from ‘@angular/core’;

@Pipe({
name: ‘pipe’ // 使用时的名称
pure: Boolean // 纯管道与非纯管道(默认为纯管道,false时为非纯管道)
})
export class TestPipe implements PipeTransform {
/**
* @param value 待处理的数据
* @param args 附加参数
* @return 处理完成的数据
*/
transform(value: any, …args: any[]): any {
return value;
}
}
我们大多数使用的是纯管道,对与非纯管道也不是太理解,可能以后用到了就明白了;官方是这样解释非纯管道的 Angular executes an impure pipe during every component change detection cycle. An impure pipe is called often, as often as every keystroke or mouse-move.

实现
代码
import { Pipe, PipeTransform } from ‘@angular/core’;
import { Host } from ‘../../entity/Host’;

/**
* 过滤:按计算机名称进行查询
*/
@Pipe({ name: ‘hostPipe’ })
export class HostPipe implements PipeTransform {

hostList: Array<Host>;

transform(value: Host[], hostName: string): any {

// 如果Value为null,则不执行
if (!value) {
return;
}
// 如果hostName为undefined,则返回value
if (!hostName) {
return value;
}

this.hostList = [];
value.forEach((host) => {
// 查询与hostName相同的
const index = host.name.indexOf(hostName);
// 如果不是-1,则相同
if (index !== -1) {
this.hostList.push(host);
}
});

return this.hostList;
}
}

效果

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理