angular2学习笔记(10)

来源:互联网 发布:力港网络 知乎 编辑:程序博客网 时间:2024/05/16 16:16

Pipes:


Angular 的管道 我觉得就是数据显示格式化。

一个简单的管道应用

import {Component} from '@angular/core'@Component({  selector: 'hero-birthday',  template: `<p>The hero's birthday is {{ birthday | date }}</p>`})export class HeroBirthday {  birthday = new Date(1988,3,15); // April 15, 1988}

代码中用{{ birthday | date }} 对birthday 进行 date方式格式化。

Angular中内建的格式化方式:

DatePipe          日期格式UpperCasePipe   全部大写格式LowerCasePipe  全部小写格式CurrencyPipe     货币格式PercentPipe  百分比格式

带参数的格式化

<p>The hero's birthday is {{ birthday | date:"MM/dd/yy" }} </p>

格式化名称后面带参数 用冒号分割,多个参数用冒号隔开。

参数可以是组件中的成员变量输出。

template: `  <p>The hero's birthday is {{ birthday | date:format }}</p>  <button (click)="toggleFormat()">Toggle Format</button>`

format是组件的成员变量,toggleFormat()是组件的点击事件响应方法。

export class HeroBirthday {  birthday = new Date(1988,3,15); // April 15, 1988  toggle = true; // start with true == shortDate  get format() { return this.toggle ? 'shortDate' : 'fullDate'}  toggleFormat() { this.toggle = !this.toggle; }}


格式化链

格式化链就是输出内容要经过多个格式化方式

<p>  The chained hero's birthday is  {{ birthday | date | uppercase}}</p>

上面的生日先进行日期格式化,在进行全部大写转化。

<p>  The chained hero's birthday is  {{  birthday | date:'fullDate' | uppercase}}</p>


自定义格式化方式

我们可以自定义需要的格式化方式

实例如下:

ExponentialStrengthPipe 格式化组件

import {Pipe, PipeTransform} from '@angular/core';/* * Raise the value exponentially * Takes an exponent argument that defaults to 1. * Usage: *   value | exponentialStrength:exponent * Example: *   {{ 2 |  exponentialStrength:10}} *   formats to: 1024*/@Pipe({name: 'exponentialStrength'})export class ExponentialStrengthPipe implements PipeTransform {  transform(value:number, args:string[]) : any {    return Math.pow(value, parseInt(args[0] || '1', 10));  }}

自定义的格式化在其他组件的应用

import {Component} from '@angular/core';import {ExponentialStrengthPipe} from './exponential-strength.pipe';@Component({  selector: 'power-booster',  template: `    <h2>Power Booster</h2>    <p>      Super power boost: {{2 | exponentialStrength: 10}}    </p>  `,  pipes: [ExponentialStrengthPipe]})export class PowerBooster { }
0 0
原创粉丝点击