Angular—pipe

2019-03-25  本文已影响0人  芝麻香油

什么是pipe

中文释义“管道”。

把数据作为输入,然后转换它,给出期望的输出。例如,将UTC时间转为指定格式;中英文的转化;大小写的转化;等等。

pipe 的使用

<p>
  {{'HELLO-WORLD WORKS!' | lowCase}}
</p>

链式pipe

<p>
  {{'HELLO-WORLD WORKS!' | lowCase | upperCase}}
</p>

自定义 pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'lowCase'
})
export class LowCasePipe implements PipeTransform {

  transform(value: any): any {
    return value.toLowerCase();
  }

}
<p>
  {{'HELLO-WORLD WORKS!' | lowCase}}
</p>

附录

  1. Angular 内置了一些管道

    • DatePipe
    • UpperCasePipe
    • LowerCasePipe
    • CurrencyPipe
    • PercentPipe
    • ...
  2. @pipe这个注解里有两个参数,即:

@Pipe({
  name: string
  pure?: boolean
})

其中name就是该pipe的名字,而pure表示该pipe是纯pipe还是非纯pipe。

自定义pipe默认都是非纯pipe。

上一篇 下一篇

猜你喜欢

热点阅读