angular2--pipe管道使用

angular2–pipe管道使用

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

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

Angular2 有一些内置管道:

五种内置管道

PipeUsageExample
DatePipedate{{ dateObj | date }} // output is 'Jun 15, 2015'
UpperCasePipeuppercase{{ value | uppercase }} // output is 'SOMETEXT'
LowerCasePipelowercase{{ value | lowercase }} // output is 'some text'
CurrencyPipecurrency{{ 31.00 | currency:'USD':true }} // output is '$31'
PercentPipepercent{{ 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 column
    table.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 string
        return eval('this.' + modifier + '(\'' + value + '\')')
    }

    // Returns 'enabled' or 'disabled' based on input value
    statusFromBoolean(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' format
        if (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() {
    }

    // 处理标记ID
    getExecFlagId(id:number) {
        switch (id) {
            case 11:
                return "未处理";
            default :
                return "";

        }
    }

    // 流程状态ID
    getProcessStatusId(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}}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值