加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular2 管道 pipe

发布时间:2020-12-17 08:39:12 所属栏目:安全 来源:网络整理
导读:前端要将数据要推入到视图中,但是HTML视图中显示的格式和数据未必完成相同,比如我们的数据都是小写,但是视图中需要显示大写,如果我们在代码中另存一组转换为大写的数据,不但会使代码变得复杂难以维护,而且可阅读性差,ng2中的管道完美的解决了这个问题

前端要将数据要推入到视图中,但是HTML视图中显示的格式和数据未必完成相同,比如我们的数据都是小写,但是视图中需要显示大写,如果我们在代码中另存一组转换为大写的数据,不但会使代码变得复杂难以维护,而且可阅读性差,ng2中的管道完美的解决了这个问题。

ng2内置了很多管道,比如DatePipe 、 UpperCasePipe 、 LowerCasePipe 、 CurrencyPipe 和 PercentPipe,可以直接在任何模板中使用。本文重点讲解自定义管道,点击观看更多管道知识

我们项目中经常需要将时间转换,但是ng2中所带的Datapipe并不合适,因为要转换为中文,比如时间转换为刚刚,1小时前,一天前,一周前等等,这时候就需要自定义管道。

写个简单的例子来说明自定义管道:将阿拉伯数字0—3转换为中文 零—三

自定义管道代码:https://github.com/nuonuoge/ng2-pipe-example(欢迎给星)

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
import { Pipe,PipeTransform } from '@angular/core'; @Pipe({name: 'i18n'}) export class i18nPipe implements PipeTransform { transform(value: number,langurage: string): string { let isen:boolean = langurage=='en'?true:false; if(value==0){ if(isen){ return 'zero'; }else{ return '零'; } }else if(value==1){ if(isen){ return 'first'; }else{ return '一'; } }else if(value==2){ if(isen){ return 'second'; }else{ return '二'; } }else if(value==3){ if(isen){ return 'third'; }else{ return '三'; } }else{ return value.toString(); } }

@Pipe装饰器告诉 Angular :这是一个管道,Pipe装饰器是从 Angular 的 core 库中引入的。Pipe中的name用来定义管道在视图中使用的名称。

PipeTransform中定义了transform,transform是管道的基本要素,用于实现管道的功能。

transform中的第一个参数value是数据的传入值,第二个参数是我们自定义的参数,而且可以定义多个参数(多个参数用法:数据|定义的管道名:第一个参数:第二个参数:第三个参数),本管道只展示了一个自定义参数(language),用来判断视图中显示中文还是英文。

ng2中管道支持链式调用,参见code3

NgModule中声明管道

 
 
  • 9
import { i18nPipe } from './i18.pipe'; @NgModule({ imports: [ BrowserModule,FormsModule,HttpModule ],declarations: [ AppComponent,i18nPipe ],providers: [ ],bootstrap: [ AppComponent ] })

ts中代码

 
 
  • 9
export class AppComponent { testi18:number[]; constructor() {} ngOnInit() { this.testi18=[0,1,2,3]; } }

HTML代码

code1:不带参数

 
 
  • 4
<div *ngFor="let item of testi18"> <span>{{item|i18n}}</span> </div>

code2:带参数

 
 
  • 4
<div *ngFor="let item of testi18"> <span>{{item|i18n:'en'}}</span> </div>

code3:带参数,链式调用

 
 
  • 4
<div *ngFor="let item of testi18"> <span>{{item|i18n:'en'|uppercase}}</span> </div>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读