Angular2 中管道@Pipe的簡單用法

在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>

pipe


Angular2 中的一些內置管道:

五種內置管道,以及Angular官方的介紹

Pipe Usage Example
DatePipe date {{ dateObj | date }} // output is ‘December 8, 2017’
UpperCasePipe uppercase {{ value | uppercase }} // output is ‘SOME TEXT’
LowerCasePipe lowercase {{ value | lowercase }} // output is ‘some text’
CurrencyPipe currency {{ 30.00 | currency:’USD’:true }} // output is ‘$30’
PercentPipe percent {{ 0.1 | percent }} //output is 10%

參考資料如下:
https://angular.io/guide/pipes
http://blog.csdn.net/u010730126/article/details/60370716
https://segmentfault.com/a/1190000008262691

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章