Angular - Pipe(Angular 內建的Pipe)

  • 1131
  • 0
  • 2018-07-25

Pipe 管線元件 (Pipe component)

 

透過官網,可以知道Angular 內建 多種Pipe:

簡單介紹其中幾樣

UpperCasePipe LowerCasePipe : 透過Pipe component 將字串轉換為大小寫

用法很簡單:

component.ts內定義文字

pipe_title = 'This is demo Visual Studio Code !';

template:component.html

<div>
    <div>{{pipe_title|uppercase}}</div>

    <div>{{pipe_title|lowercase}}</div>
</div>

其中在template內寫Pipe可善用intellisense

DecimalPipe

詳細介紹可見 官網

這邊節錄一些重點

{{ value_expression | number [ : digitsInfo [ : locale ] ] }}

value_expression:要轉換的運算結果

number:pipe 名稱(雖然是DecimalPipe ,但是實際使用要用number)

digitsInfo :包在中括號內,表示非必輸(Optional),要轉換的規則

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

minIntegerDigits:最少的整數位數顯示幾位數

minFractionDigits:最少小數位數顯示幾位數

maxFractionDigits:最多小數位數顯示幾位數

locale:可輸入locale_ID 來依照當地的規則轉換數字

官網內有很詳細的範例可供參考

 

JsonPipe

非常方便偵錯後端提供的Json物件,

例如:

先在component.ts內準備一段JSON的資料

data = [
    {
      title: 'Google',
      'href-link': 'http://www.google.com.tw',
      date: '2018/05/10',
      content: '<p>Google Content</p>'
    },
    {
      title: 'Facebook',
      'href-link': 'http://www.facebook.com.tw',
      date: '2018/05/11',
      content: '<p>Facebook Content</p>'
    },
    {
      title: 'Yahoo',
      'href-link': 'http://www.yahoo.com.tw',
      date: '2018/05/12',
      content: '<p>Yahoo Content</p>'
    }
  ];

然後在template裡面利用Structure Directive:ngFor 將資料呈現在畫面上

<div>
    <div id="id_{{_idx}}" *ngFor="let item of data;let _idx = index">
        <a [href]="item['href-link']">{{item.title}}</a>
        <br>
        <span>Date:{{item.date}}</span>
        <span [innerHTML]="item.content"></span>
        <pre>
          {{item}}
        </pre>
    </div>
</div>

如果我想偵錯,想看一下後端丟什麼資料到前端,我用 <pre>{{item}}</pre> 把資料呈現在畫面上

結果只會看到object

這時候就可以使用JsonPipe

將<pre>{{item}}</pre> 改為 <pre>{{item|json}}</pre>

就可以看到正確的資料

 

slicePipe : 可以切割字串或者是陣列、物件陣列

{{ value_expression | slice : start [ : end ] }}

value_expression  => 要切割的字串 或者是 陣列

start :必輸,要切割的起始字元(OR陣列的INDEX) ,如果輸入負數就是從後面開始算起

end :非必輸,如果沒有輸入的話就會直接切到最後一個字元OR陣列的最後一個element