angular2中管道@pipe的簡單使用

需求

使用過濾,實現前臺查詢。

Angular2中有各類各樣的類修飾器,好比:@App@Component@input@output等等,最近須要用到數據過濾用到了管道@Pipe,下面記錄簡單@Pipe的簡單用法。數組

什麼是pipe

就是管道,簡單來講,管道的做用就是傳輸。而且不一樣的管道具備不一樣的做用。(其實就是處理數據)。ide

angular中自帶的pipe函數

管道 功能
DatePipe 日期管道,格式化日期
JsonPipe 將輸入數據對象通過JSON.stringify()方法轉換後輸出對象的字符串
UpperCasePipe 將文本全部小寫字母轉換成大寫字母
LowerCasePipe 將文本全部大寫字母轉換成小寫字母
DecimalPipe 將數值按照特定的格式顯示文本
CurrentcyPipe 將數值進行貨幣格式化處理
SlicePipe 將數組或者字符串裁剪成新子集
PercentPipe 將數值轉百分比格式

pipe用法

  • {{ 輸入數據 | 管道 : 管道參數}} (其中‘|’是管道操做符)
  • 鏈式管道 {{ 輸入數據 | date | uppercase}}
詳細內容請參考 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;
    }
}

clipboard.png

  • 效果

clipboard.png

相關文章
相關標籤/搜索