《Angular2入门系列基础》——pipe管道数据类型

来源:互联网 发布:西安长臂猿网络 编辑:程序博客网 时间:2024/05/17 07:33

【前言】

    angular2数据类型校验可以使用管道,管道有内置管道(DatePipe,UpperCasePipe,LowerCasePipe和PercentPipe),它们可以用于全部的模板中;链式管道(指多种管道组合在一起,以完成潜在的有用功能);自定义管道可以定义一些特定的类型为自己所用。

【内容】

1.内置管道使用:

import { Component } from '@angular/core';@Component({  selector: 'hero-birthday',  template: `<p>The hero's birthday is {{ birthday | date }}</p>`})export class HeroBirthdayComponent {  birthday = new Date(1994, 3, 15); // April 15, 1988}
管道插座符(|)流动到右侧的date管道中。

2.链式管道使用:

The chained hero's birthday is{{ birthday | date | uppercase}}
3.自定义的管道:(和内置管道的用法一致,但是需要在在module中声明一下)
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: 'cylStringPipe'})export class CylStringPipe implements PipeTransform {  transform(value: number, exponent: string): number {    let exp = parseFloat(exponent);    return Math.pow(value, isNaN(exp) ? 1 : exp);  }}

组件中引入:

import { Component } from '@angular/core';@Component({  selector: 'power-booster',  template: `    <h2>Power Booster</h2>    <p>Super power boost: {{2 | cylStringPipe: 10}}</p>  `})export class PowerBoosterComponent { }


【总结】

   感谢您的时间,欢迎提出问题!

原创粉丝点击