[Angular 2] Understanding Pure & Impure pipe
First, how to use a build in pipe:
<div class="pipe-example"> <label>Uppercase Pipe: {{ message | uppercase }}</label> </div> <div class="pipe-example"> <label>Lowercase Pipe: {{ message | lowercase }}</label> </div> <div class="pipe-example"> <label>Slice Pipe: {{ message | slice:0:5 }}</label> </div> <div class="pipe-example"> <label>Date Pipe: {{ date | date:'yyyy-MMM-dd' }}</label> </div> <div class="pipe-example"> <label>Number Formatting: {{ pi | number:'5.1-2' }}</label> </div> <div class="pipe-example"> <label>Percent Pipe: {{ percentage | percent:'2.1-2' }}</label> </div> <div class="pipe-example"> <label>Currency Pipe: {{ amount | currency:'USD':true:'2.1-2' }}</label> </div>
Then how to create a custom pipe:
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'sort' }) export class SortPipe implements PipeTransform { transform(value: any[], args): any[] { let sorted = [ ...value ].sort(); if(args.length > 0 && args === "DESC"){ sorted = sorted.reverse(); } return sorted; } }
Notice here, we use:
let sorted = [
...value
].sort();
The reason doing this is because sort() is mutate opreation, once you apply sort(), it will mutate the original data, which is not good. So here we create a copy of data and apply sort() fucntion to enhance immutatbility.
Pure and Impure:
See example at: https://angular.io/resources/live-examples/pipes/ts/plnkr.html
Pure pipe it means:
It won't go thought Angular Change Detection if the primitive type reference doesn't change.
if (this.mutate) { // Pure pipe won't update display because heroes array reference is unchanged // Impure pipe will display this.heroes.push(hero); } else { // Pipe updates display because heroes array is a new object this.heroes = this.heroes.concat(hero); }
So if 'this.mutate' is ture, then we mutate this.heros array, so primitive type (array) reference is changed. So this will trigger change detection. So that, everytime you add a hero into the this.hero, piped result will update.
If this.mutate is false, then reference won't change, therefore, if you add new hero, even set 'can fly' tag to ture, it won't update the piped result.
Impure pipe:
Angular executes an impure pipe during every component change detection cycle. An impure pipe will be called a lot, as often as every keystroke or mouse-move.
To set pure or impure you just need to add a pure flag:
@Pipe({ name: 'sort', pure: true //false })
Default is ture.
So when build a custom pipe, you need to decide whether it should be pure or impure.
相关文章
- Hook技术【移动端&&PC端详解】「建议收藏」
- 沐创携第一代DPU智能网卡亮相第二届SmartNIC & DPU 技术创新峰会
- RabbitMQ学习笔记(五)——RabbitMQ集群搭建&入门
- CPU C-state & cpuidle driver[通俗易懂]
- ECCV 2022 | 摆脱部件标签依赖,上科大&ZMO.AI提出分部件3D人体重建与驱动新方法UNIF
- H3C路由交换 Smart Link & Monitor Link
- 数字化 IT 从业者知识体系 | 软件交付与协作 —— ITIL V1 & ITIL V2
- ssdp_amp DDOS攻击.c
- AMP与Oracle结合提升数据库性能($amp oracle)