angular2--pipe管道使用

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: `
{{gender | i18nSelect: inviteMap}} </div>`}) export class I18nSelectPipeComponent { gender: string = 'male'; inviteMap: any = {'male': 'Invite him.', 'female': 'Invite her.', 'other': 'Invite them.'}; }

管道可以多级(链式)

Today is {{ today | date:'fullDate' | uppercase}}.

异步参数的管道

官网介绍:

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: `
promise|async: Wait for it... {{ greeting | async }}
` }) 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: '
observable|async: Time: {{ time | async }}
'
}) export class AsyncObservablePipeComponent { time = new Observable((observer: Subscriber) => { 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: `
    

Hello, {{ name | async }}

Your Friends are:
  • {{friend}}
` }) class AsyncStuffComponent { name = Promise.resolve('Misko'); friends = Observable.of(['Igor']); }

Becomes:

Hello, Misko

Your Friends are:
  • Igor

网上的自建管道

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}}

你可能感兴趣的:(前端那些事,angular2)