需求使用过滤,实现前台查询。在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-pipepipe的基本语法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; }}效果