ng2 内置pipe 一览

ng2 内置pipe 一览

ng2 内置pipe 一览_第1张图片

pipe说明:

  1. UpperCasePipe --- Transforms text to uppercase.
  2. LowerCasePipe --- Transforms text to lowercase.
  3. JsonPipe --- Converts value into JSON string.
  4. CurrencyPipe --- Formats a number as currency using locale rules.
  5. DatePipe --- Formats a date according to locale rules.
  6. SlicePipe --- Creates a new List or String containing a subset (slice) of the elements.

  1. TitleCasePipe --- Transforms text to uppercase.
  2. PercentPipe --- Formats a number as a percentage according to locale rules.
  3. DecimalPipe --- Formats a number according to locale rules.
  4. AsyncPipe --- Unwraps a value from an asynchronous primitive. observable_or_promise_expression | async

和ng1对比如下:


ng2 内置pipe 一览_第2张图片

总结:

  1. ng1中称为filter,ng2中称为pipe 功能类似
  2. ng1中的 limitTo被替换为 slicePipe
  3. ng2 新增了 asyncPipe,decimalPipe等

  • digitInfo is a string which has a following format:

  • {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

  • (数值位数限制,整数最小位数.小数最小位数-小数最大位数)

  • minIntegerDigits is the minimum number of integer digits to use. Defaults to 1. 整型数最小的位数

  • minFractionDigits is the minimum number of digits after fraction. Defaults to 0. 小数点后最小的位数

  • maxFractionDigits is the maximum number of digits after fraction. Defaults to 3. 小数点后最大的位数

      

    {{'abcd' | uppercase}}

    {{'ABcd' | lowercase}}

    {{'{a:1}' | json}}

    {{'1000' | currency}}

    {{'1000' | currency:CNY:true}}

    {{date | date:'y-MM-d'}}

    {{'ABcd' | slice:0:2}}


    {{'abDfEf' | titlecase}}

    {{0.2611123 | percent}}

    {{0.26 | percent:'.2'}}

    {{0.262323 | percent:'.2-4'}}

结果如下:

![](http://upload-images.jianshu.io/upload_images/3915498-364df115665cba9b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

AsyncPipe例子如下:

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

    @Component({
      selector: 'app-pipes-app-component',
      templateUrl: './pipes-app-component.component.html',
      styleUrls: ['./pipes-app-component.component.css']
    })
    export class PipesAppComponentComponent implements OnInit {
      promise:Promise;
      constructor() {
        this.promise = new Promise(function(resolve, reject) {
          setTimeout(function() {
            resolve("Hey, I'm from a promise.");
          }, 2000)
        });
      }
    
      ngOnInit() {
      }
    
    }


    

pipes-app-component works!

{{ promise | async}}

两秒后显示:Hey, I'm from a promise.

参考:

https://auth0.com/blog/angular2-series-working-with-pipes/

https://angular.io/api/common/AsyncPipe

你可能感兴趣的:(ng2 内置pipe 一览)