[转]Angular2 使用管道Pipe以及自定义管道格式数据

本文转自:https://www.pocketdigi.com/20170209/1563.html

 

管道(Pipe)可以根据开发者的意愿将数据格式化,还可以多个管道串联。

纯管道(Pure Pipe)与非纯管道(Impure Pipe)

管道分纯管道(Pure Pipe)和非纯管道(Impure Pipe)。默认情况下,管道都是纯的,在自定义管道声明时把pure标志置为false,就是非纯管道。如:

@Pipe({
  name: 'sexReform',
  pure:false
})

 

纯管道和非纯管道的区别:

  • 纯管道:

    Angular只有检查到输入值发生纯变更时,才会执行纯管道。纯变更指的是,原始类型值(String,Number,Boolean,Symbol)的改变,或者对象引用的改变(对象值改变不是纯变更,不会执行).

  • 非纯管道

    Angular会在每个组件的变更检测周期执行非纯管道。所以,如果使用非纯管道,我们就得注意性能问题了。

管道使用语法

{{expression | pipe : arg}}
如果是链式串联:
{{expression | pipe1 : arg | pipe2 | pipe3 }}

常用内置管道

管道类型功能
DatePipe 纯管道 日期格式化
JsonPipe 非纯管道 使用JSON.stringify()将对象转成json字符串
UpperCasePipe 纯管道 将文本中的字母全部转在大写
LowerCasePipe 纯管道 将文本中的字母全部转成小写
DecimalPipe 纯管道 数值格式化
CurrencyPipe 纯管道 货币格式化
PercentPipe 纯管道 百分比格式化
SlicePipe 非纯管道 数组或字符串取切割
  • DatePipe

    语法:{{expression | date:format}}
    expression支持日期对象、日期字符串、毫秒级时间戳。format是指定的格式,常用标志符:

    • y 年 y使用4位数字表示年份(2017),yy使用两位数字表示(17)
    • M 月 M 1位或两位数字(2或10、11、12),MM 两位数字表示,前面补0(02)
    • d 日 d 一位或两位数字(9) dd两位数字,前面补0(09)
    • E 星期 EEE 三位字母缩写的星期 EEEE 星期全称
    • j 12小时制时间 j (9 AM) jj (09 AM)
    • h 12小时制小时 h(9) hh (09)
    • H 24小时制小时 H(9) HH (09)
    • m 分 m (5) mm (05)
    • s 秒 s (1) ss (01)
    • z 时区 z China Standard Time
  • DecimalPipe
    语法:{{expression | number[: digiInfo] }}
    digiInfo格式:
    {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
    即:整数位保留最小位数.小数位保留最小位数-小数位最大保留位置
    默认值: 1.0-3

  • CurrencyPipe
    语法:{{expression | currency[: currencyCode[: symbolDisplay[: digiInfo]]] }}
    digiInfo格式与DecimalPipe相同,不再解释。
    currencyCod是指货币代码,其值为ISO 4217标准,人民币CNY,美元USD,欧元 EUR.
    symbolDisplay 是一个布尔值,true时显示货币符号($¥) false显示货币码

  • PercentPipe
    语法:{{expression | percent[: digiInfo] }}
    digiInfo格式与DecimalPipe相同,不再解释。

  • SlicePipe
    语法:{{expression | slice: start [: end] }}
    expression 可以是一个字符串或数组。字符串时,该管道调用String.prototype.slice()方法截取子串。如果是数组,调用Array.prototype.slice()方法取数组子元素。

自定义管道

除了使用内置的管道,还可以通过自定义管道实现更复杂的功能。
创建管道:
ng g pipe sexReform
angular-cli会帮我们创建SexReformPipe管道,这个管道的功能是根据malefemale返回中文的
代码:

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
  name: 'sexReform',
  //非纯管道
  pure:false
})
export class SexReformPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    let chineseSex;
    switch (value) {
      case 'male':
        chineseSex = '男';
        break;
      case 'female':
        chineseSex = '女';
        break;
      default:
        chineseSex = '未知性别';
        break;

    }
    return chineseSex;
  }

}

重点在于实现PipeTransform接口的transform方法,定义为非纯管道仅用于演示,非纯管道对性能影响较大,尽量避免。

演示代码

组件:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-pipe',
  templateUrl: './pipe.component.html',
  styleUrls: ['./pipe.component.css']
})
export class PipeComponent implements OnInit {
  date=new Date();
  money=5.9372;
  object={title:'ffff',subTitle:'subtitlefff'};
  str='abcdABCD';
  percent=0.97989;
  constructor() { }

  ngOnInit() {
  }

}

模板:

  <p>
  {{date| date:'y-MM-dd HH:mm:ss'}} <br />
  {{object| json }} <br />
  {{str| uppercase }} <br />
  {{str| lowercase }} <br />
  {{money| number:'2.4-10' }} <br />
  {{money| number:'5.1-2' }} <br />
  {{money| currency:'CNY':false:'1.1-2' }} <br />
  {{percent| percent:'1.1-2' }} <br />
  {{str| slice:1:3 }} <br />
  {{'female'| sexReform }} <br />
</p>

© 2017, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记

posted on 2018-09-30 10:24  freeliver54  阅读(369)  评论(1编辑  收藏  举报

导航