angular2–pipe管道使用

官网地址(中文):https://angular.cn/docs/ts/latest/guide/pipes.html

官网地址(中文):https://angular.io/docs/ts/latest/guide/pipes.html

Angular2 有一些内置管道:

五种内置管道

Pipe Usage Example
DatePipe date {{ dateObj | date }} // output is 'Jun 15, 2015'
UpperCasePipe uppercase {{ value | uppercase }} // output is 'SOMETEXT'
LowerCasePipe lowercase {{ value | lowercase }} // output is 'some text'
CurrencyPipe currency {{ 31.00 | currency:'USD':true }} // output is '$31'
PercentPipe percent {{ 0.03 | percent }} //output is %3

I18nSelectPipe

将输入值,依照一个map来转换,显示匹配值

用法: i18nSelect:mapping

@Component({selector: 'i18n-select-pipe', template: `<div>{{gender | i18nSelect: inviteMap}} </div>`})
export class I18nSelectPipeComponent {gender: string = 'male';inviteMap: any = {'male': 'Invite him.', 'female': 'Invite her.', 'other': 'Invite them.'};
}

管道可以多级(链式)

<p>Today is {{ today | date:'fullDate' | uppercase}}.</p>

异步参数的管道

官网介绍:

What it does

Unwraps a value from an asynchronous primitive.

How to use

observable_or_promise_expression | async

NgModule

CommonModule

Description

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

Examples

This example binds a Promise to the view. Clicking the Resolve button resolves the promise.

@Component({selector: 'async-promise-pipe',template: `<div><code>promise|async</code>: <button (click)="clicked()">{{ arrived ? 'Reset' : 'Resolve' }}</button><span>Wait for it... {{ greeting | async }}</span></div>`
})
export class AsyncPromisePipeComponent {greeting: Promise<string> = null;arrived: boolean = false;private resolve: Function = null;constructor() { this.reset(); }reset() {this.arrived = false;this.greeting = new Promise<string>((resolve, reject) => { this.resolve = resolve; });}clicked() {if (this.arrived) {this.reset();} else {this.resolve('hi there!');this.arrived = true;}}
}

It’s also possible to use async with Observables. The example below binds the time Observable to the view. The Observable continuously updates the view with the current time.

@Component({selector: 'async-observable-pipe',template: '<div><code>observable|async</code>: Time: {{ time | async }}</div>'
})
export class AsyncObservablePipeComponent {time = new Observable<string>((observer: Subscriber<string>) => {setInterval(() => observer.next(new Date().toString()), 1000);});
}

来自:http://stackoverflow.com/users/3708596/everettss 的案例

import { Component } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';@Component({selector: 'async-stuff',template: `<h1>Hello, {{ name | async }}</h1>Your Friends are:<ul><li *ngFor="let friend of friends | async">{{friend}}</li></ul>`
})
class AsyncStuffComponent {name = Promise.resolve('Misko');friends = Observable.of(['Igor']);
}

Becomes:

<h1>Hello, Misko</h1>
Your Friends are:
<ul><li>Igor</li>
</ul>

网上的自建管道

Use case scenario:

A table view consists of different columns with different data format that needs to be transformed with different pipes.

来自http://stackoverflow.com/users/871956/borislemke

table.component.ts

...
import { DYNAMIC_PIPES } from '../pipes/dynamic.pipe.ts';@Component({...pipes: [DYNAMIC_PIPES]
})
export class TableComponent {...// pipes to be used for each columntable.pipes = [ null, null, null, 'humanizeDate', 'statusFromBoolean' ],table.header = [ 'id', 'title', 'url', 'created', 'status' ],table.rows = [[ 1, 'Home', 'home', '2016-08-27T17:48:32', true ],[ 2, 'About Us', 'about', '2016-08-28T08:42:09', true ],[ 4, 'Contact Us', 'contact', '2016-08-28T13:28:18', false ],...]...}

dynamic.pipe.ts

import {Pipe,PipeTransform
} from '@angular/core';
// Library used to humanize a date in this example
import * as moment from 'moment';@Pipe({name: 'dynamic'})
export class DynamicPipe implements PipeTransform {transform(value:string, modifier:string) {if (!modifier) return value;// Evaluate pipe stringreturn eval('this.' + modifier + '(\'' + value + '\')')}// Returns 'enabled' or 'disabled' based on input valuestatusFromBoolean(value:string):string {switch (value) {case 'true':case '1':return 'enabled';default:return 'disabled';}}// Returns a human friendly time format e.g: '14 minutes ago', 'yesterday'humanizeDate(value:string):string {// Humanize if date difference is within a week from now else returns 'December 20, 2016' formatif (moment().diff(moment(value), 'days') < 8) return moment(value).fromNow();return moment(value).format('MMMM Do YYYY');}
}export const DYNAMIC_PIPES = [DynamicPipe];

table.component.html

<table><thead><td *ngFor="let head of data.header">{{ head }}</td></thead><tr *ngFor="let row of table.rows; let i = index"><td *ngFor="let column of row">{{ column | dynamic:table.pipes[i] }}</td></tr>
</table>

Result


| ID | Page Title     | Page URL    | Created          | Status     |
---------------------------------------------------------------------
|  1 | Home           | home        | 4 minutes ago    | Enabled    |
|  2 | About Us       | about       | Yesterday        | Enabled    |
|  4 | Contact Us     | contact     | Yesterday        | Disabled   |
---------------------------------------------------------------------

我写的管道

管道写成了module

思路:写成module,使用imports导入。使用的时候,如果参数过多,先转换为json格式,在当做参数传入我们自建的管道。

/*** Created by free on 17/1/6.*/
import { Component, NgModule} from '@angular/core';
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'flag2NamePipe'})
export class Flag2NamePipe implements PipeTransform {constructor() {}// 处理标记IDgetExecFlagId(id:number) {switch (id) {case 11:return "未处理";default :return "";}}// 流程状态IDgetProcessStatusId(id:number) {//console.log("流程状态",id);switch (id) {case 1:return "个人稿";default :return "";}}transform(value) {switch (JSON.parse(value).topmenuselect) {case 1:return this. getProcessStatusId(JSON.parse(value).id);}return "";}
}
@NgModule({imports: [],exports: [Flag2NamePipe],declarations: [Flag2NamePipe]
})
export class Flag2NamePipeModule {}

使用

ts文件

@NgModule({imports: [...Flag2NamePipeModule,...],exports: [StoryDetailComponent],declarations: [StoryDetailComponent]
})
export class StoryDetailModule {
}

模板文件

                        {{{'execFlagId':story.execFlagId,'topmenuselect':topmenuselect,'roleType':user.roleType,'processStatusId':story.processStatusId,'unionStatusId':story.unionStatusId,'processExId':story.processExId} | json | flag2NamePipe}}

angular2--pipe管道使用相关推荐

  1. php+管道+pipe管道,angular2+管道pipe

    一.什么是Pipe? 就是管道,简单来说,管道的作用就是传输.并且不同的管道具有不同的作用.(其实就是处理数据) 二.pipe用法 {{ 输入数据 | 管道 : 管道参数}}  (其中'|'是管道操作 ...

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

    本文转自:https://www.pocketdigi.com/20170209/1563.html 管道(Pipe)可以根据开发者的意愿将数据格式化,还可以多个管道串联. 纯管道(Pure Pipe ...

  3. 在.NET程序中使用PIPE(管道技术)

    在.NET程序中使用PIPE(管道技术) 这几天不知道做什么, 受朋友影响, 看完了"新天龙八部", 深受感动, 所以打算做点好事. =) 关于PIPE的应用, 其实原理很简单, ...

  4. 嵌入式linux的学习笔记-pipe管道(二)

    今天学习了一下pipe管道,用于父子或者相关联的两个进程之间的通讯,pipe使用 pipe()函数建立,必须用于fork建立的进程中,并且需要在fork之前调用,否则是没有效果的,下面是一个例子和用法 ...

  5. Linux进程通信(一)——pipe管道

    本章内容 采用pipe管道如何进行进程之间的通信 pipe管道进程通信的规则和限制 Linux中pipe管道的实现机制和管理pipe管道的结构体 什么是进程通信 进程通信就是两个进程之间进行数据交换, ...

  6. 【Linux进程间通信】二、pipe管道

    pipe管道 1. 什么是管道 2. pipe()函数创建管道 2.1 函数原型 2.2 工作原理 2.3 通过实战分析管道的特性 3. 管道的读写行为 4. 管道(缓冲区)大小 5. 管道的优缺点 ...

  7. Pipe(管道)的一些理解

    Pipe(管道)的一些理解 管道的概念 管道是操作系统中常见的一种进程间通信方式,它使用于所有POSIX系统以及Windows系列产品. 管道也是unix ipc的最老形式,管道有两种限制: 数据自己 ...

  8. 驱动通信:通过PIPE管道与内核层通信

    在本人前一篇博文<驱动开发:通过ReadFile与内核层通信>详细介绍了如何使用应用层ReadFile系列函数实现内核通信,本篇将继续延申这个知识点,介绍利用PIPE命名管道实现应用层与内 ...

  9. javaNIO实战9----> java NIO的Pipe管道实战

    1.Pipe管道通常使用在对条线程之间共享数据的场景,模型如下图所示: 2.实战案例 @Testpublic void nioPipe() throws IOException, Interrupte ...

  10. angular2+ 自定义pipe管道实例--定义全局管道及使用

    首先到项目目录下ng g pipe pipe/myslice 就会在app目录下生成一个pipe文件夹文件夹下有myslice.pipe.ts文件,如果没有也可以自己手动新建 然后需要再app.mod ...

最新文章

  1. mac下找不到.m2文件解决方法
  2. Linux_Bash脚本基础
  3. laravel 5.5 的相关字符串辅助函数
  4. 数位dp:Educational Codeforces Round 53 (Rated for Div. 2) E. Segment Sum
  5. 4个在2020年持续发展的数据中心冷却趋势
  6. MySQL带IN关键字的子查询
  7. 智行火车票能否把用户的敏感信息屏蔽?
  8. (72)信号发生器DDS方波设计 (二)(第15天)
  9. transformers Tokenizer
  10. WIN10常用快捷键(打开资源管理器、显示桌面、截图)
  11. Vim-latex 插件 的安装
  12. AutoLISP恢复系统变量到默认值
  13. 结构方程模型_结构方程模型(Structural Equation Model, SEM) 三下
  14. 微信小程序获取二维码scene报错40129
  15. 区块链中的节点是什么意思?
  16. 教你如何在Sco Unix5.05安装大硬盘(启动输入硬盘参数方法)
  17. 使用thinkadmin内置WeChatDeveloper发送公众号模板消息
  18. 怎样才能画好人物手臂?画好人物手臂有哪些技巧?
  19. 绎维软件F-One获得B轮融资,华创资本领投,齐银基金跟投
  20. 汇编语言实现简单的人机问答

热门文章

  1. 数据科学环境Anaconda及其相关组件介绍
  2. 关于使用layui中的tree的一个坑
  3. HTTP深入浅出个人总结
  4. VSftp常规服务配置
  5. B12-UIAlertController(NS_CLASS_AVAILABLE_IOS(8_0))。
  6. Spring3.2.4集成quartz2.2.1定时任务(demo).
  7. 在nginx中用X-Accel-Redirect response header控制文件下载
  8. 火狐插件火狐***插件将Firefox变成***工具的七个插件
  9. Silverlight:应用程序模型
  10. Linux程序在预处理、编译、汇编、链接、运行步骤的作用