angular pipe
管道,通過邏輯簡單處理模板中數據的一種方式,用法簡單,是開發中很重要的簡化代碼的利器。(原文閱讀)
元數據說明
-
name: string–在模板中綁定時使用的管道名。 通常使用 lowerCamelCase拼寫方式,因為名字中不允許包含減號(-)。
-
pure?: boolean–為 true時,該管道是純管道,也就是說 transform()方法只有在其輸入參數變化時才會被調用。管道默認都是純管道。
用法
{{ exp | myPipe }}內置管道
Angular有很多內置管道供我們使用,下面是常用的內置管道(更多):
- AsyncPipe --自動訂閱模板中的Observable或Promise
- CurrencyPipe --把數字轉換成金額字符串, 根據本地化規則進行格式化
- DatePipe --根據區域設置規則格式化日期值
- DecimalPipe --數字轉字符串,并可以指定格式
- KeyValuePipe --使ngFor可以循環Object或Map對象
- JsonPipe --把一個值轉換成JSON字符串格式。在調試時很有用。
- TitleCasePipe --把首字母大寫,其它小寫
- SlicePipe --截取Array或String
- PercentPipe --數字轉百分比
- LowerCasePipe和UpperCasePipe --轉化小寫或大寫
KeyValuePipe
以前我們ngFor的時候都是循環的數組,通過KeyValuePipe,我們可以循環Object或Map對象。
創建pipe組件:
ng g c components/pipe -s創建普通對象以及Map對象:
// pipe.component.ts ... export class PipeComponent implements OnInit {obj:{[key: number]: string} = {2: 'foo', 1: 'bar'};map = new Map([[2, 'foo'], [1, 'bar']]);... }循環:
<!-- pipe.component.html --> <div class="pipe"><div *ngFor="let item of obj | keyvalue">{{item.key}}: {{item.value}}</div><div *ngFor="let item of map | keyvalue">{{item.key}}: {{item.value}}</div> </div>自定義管道
下面定義一個將數字指數化的管道exponentialStrength。如{{5 | exponentialStrength: 3}},表示5的3次方。
ng g p pipe/exponentialStrengthtips: 執行上面的命令后,cli工具會自動引入相應模塊到app.module.ts中
修改代碼:
// exponential-strength.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({// 管道名字name: 'exponentialStrength' }) export class ExponentialStrengthPipe implements PipeTransform {// 實現transform方法,返回處理過后的數字transform(value: number, exponent?: number): number {return Math.pow(value, isNaN(exponent) ? 1 : exponent);} }創建一個管道就這么簡單,我們就能在任意模版中使用。
<!-- 5的3次方 --> <p>{{5 | exponentialStrength: 3}}</p> <!-- 8的1次方 --> <p>{{8 | exponentialStrength}}</p>非純管道
默認的管道都是純的,Angular會忽略復合對象中的變化,即管道只會檢查原始值或對象引用。
可如果數組中的元素變化,增刪改,由于引用沒有變化,所以不會執行管道的邏輯。
我們將通過下面一個簡單的例子來說明這個問題.
創建一個篩選數字大于0的管道:
ng g p pipe/numberGtZero實現管道邏輯:
// number-gt-zero.pipe.ts ... @Pipe({name: 'numberGtZero'}) export class NumberGtZeroPipe implements PipeTransform {transform(arr: any[]): number[] {const result: number [] = [];arr.map(n => {if (!isNaN(n) && n > 0) {result.push(n);}});return result;} }使用管道:
// pipe.component.ts export class PipeComponent implements OnInit {numArr = [-6,7,6,-4,-3,0,3,1,-2];// ...addNumber() {const plusOrMinus = Math.random() < 0.5 ? -1 : 1; const randomNum = Math.floor(Math.random() * 10);this.numArr.push(plusOrMinus * randomNum);console.log(this.numArr);} } <button class="btn btn-primary" (click)="addNumber()">添加數字</button><br> <!-- 只顯示大于0的數 --> <span *ngFor="let n of (numArr | numberGtZero)">{{n}}</span>頁面表現:
上面的例子我們可以得出結論:pipe對于復雜類型數據,由于引用沒有變化,所以不會執行管道的邏輯。
我們可以通過數組的操作來解決這個問題,但是最簡便的方式肯定是官方的做法,修改pure參數為false:
// number-gt-zero.pipe.ts ... @Pipe({name: 'numberGtZero',pure: false })總結
官方內置管道能滿足日常基本需求,KeyValuePipe用于循環對象、Map;
自定義管道時,建議使用cli命令生成模版,不然將手動引入組件是個麻煩事;
當管道篩選的數據是復雜類型時,請將pure參數設置為false。
歡迎關注我的公眾號,公眾號將第一時間更新angular教程:
總結
以上是生活随笔為你收集整理的angular pipe的全部內容,希望文章能夠幫你解決所遇到的問題。