Angular--Pipe管道理解及用法及自定義管道

1.什麼是Pipe?
       就是管道,簡單來說,管道的作用就是傳輸。並且不同的管道具有不同的作用。(其實就是處理數據)

2.pipe用法
       {{ 輸入數據 | 管道 : 管道參數}}  (其中‘|’是管道操作符)

3.Angular自帶的pipe函數

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

例如: person.name | uppercase

       左邊和右邊都有對應的數據。person.name是一個容器,容器裝了一個name,當name碰到管道之後會把name給uppercase,uppercase的作用就是把name轉換。左邊輸出 右邊接收,右邊再輸出。

4.簡單使用pipe自帶函數

html(不使用管道的情況):<div>{{birthday}}</div>
export class PipeTestComponent implements OnInit {
  birthday = new Date();
}

運行結果:

html(使用pipe後):<div>{{birthday | date}}</div>


結果:

5.自定義管道:

首先打開Node.js cd到項目文件夾下,輸入指令  ng g pipe pipe-name

成功後會出現兩個文件:

       pipe-name.pipe.spec.ts   //測試

       pipe-name.pipe.ts     //用來寫自定義pipe

pipe-name.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'pipeName'
})
export class PipeNamePipe implements PipeTransform {
  transform(code: number) {
    if (code === 0) {
      return '鎖定';
    }
    if ( code === 1) {
      return '正常';
    }
    if (code === 2) {
      return '過期';
    }
  }

}


// 文件使用處,直接調用名稱即可
<div>{{code | pipeName}}</div>

// ts文件中定義好code
code = 2

運行結果:

發佈了106 篇原創文章 · 獲贊 24 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章