angular2--pipe管道使用
angular2–pipe管道使用
官網地址(中文):https://angular.cn/docs/ts/latest/guide/pipes.html
官網地址(中文):https://angular.io/docs/ts/latest/guide/pipes.html
Angular2 有一些內置管道:
五種內置管道
| 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管道使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 开发工具链(国内项目)(持续更)
- 下一篇: 关于angular2更新时机的一些发现