使用过滤,实现前台查询。
在Angular2
中有各类各样的类修饰器,好比:@App
,@Component
,@input
,@output
等等,最近须要用到数据过滤用到了管道@Pipe
,下面记录简单@Pipe
的简单用法。数组
pipe
?就是管道,简单来讲,管道的做用就是传输。而且不一样的管道具备不一样的做用。(其实就是处理数据)。ide
angular
中自带的pipe
函数管道 | 功能 |
---|---|
DatePipe | 日期管道,格式化日期 |
JsonPipe | 将输入数据对象通过JSON.stringify()方法转换后输出对象的字符串 |
UpperCasePipe | 将文本全部小写字母转换成大写字母 |
LowerCasePipe | 将文本全部大写字母转换成小写字母 |
DecimalPipe | 将数值按照特定的格式显示文本 |
CurrentcyPipe | 将数值进行货币格式化处理 |
SlicePipe | 将数组或者字符串裁剪成新子集 |
PercentPipe | 将数值转百分比格式 |
pipe
用法
详细内容请参考
angular官方文档
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; } }